Adam Anderson

Adam Anderson :: Blog

Twitter LinkedIn Google+

Bootstrapping an AngularJS app in Rails 4.0 - Part 5

November 20, 2013 AngularJS Rails Tutorial

Apologies for the delay getting part 5 out! I have been super busy with finishing up work on my last job, starting a new one, and family obligations. I am hoping to bring the cadence of these posts back up to about one per month, life permitting.


The full GitHub repository for this tutorial is available here

Introduction

This is part five of my tutorial covering building an Angular and Rails blog application from scratch. We will start where we left off in part 4. In the last post, we set up a shared AngularJS service that allowed a single point of access to API data for all client-side Angular controllers. In this post, we will continue to build out the shared AngularJS service and Rails API, implementing the functionality to create posts. We will also touch on AngularJS promises for the first time and leverage them to help deal with asynchronous data loading.


Creating new posts from the client

Before getting too deeply into implementing the new post functionality, we need to do a bit of refactoring to accommodate the functionality. Let's start by adding a navigation bar to the top of our homepage. To do this, we must first move the container class out of the ng-view div in our main index view:

app/views/main/index.html.erb

<div ng-view>
</div>


This will allow the navigation bar to be the full width of the browser window. Now, let's implement the navigation bar itself. (For more information about how to set up or customize a Bootstrap top navbar, check out the documentation here.) Make sure to remember to add the margin-top: 40px style to the container div—this ensures that the navbar and page content do not overlap.

app/assets/templates/mainIndex.html

<div class="navbar navbar-fixed-top">
  <div class="navbar-inner">
    <a href="#" class="brand">My blog</a>
    <ul class="nav pull-right">
      <li><a ng-click="navNewPost()">New Post</a></li>
    </ul>
  </div>
</div>

<div class="container" style="margin-top: 40px">
  <h1 class="text-center">My blog</h1>
  <div class="row" ng-repeat="post in data.posts">
      <h2><a ng-click="viewPost($index)">{{ post.title }}</a></h2>
      <p>{{ post.contents }}</p>
  </div>
</div>


Notice that we have added an ng-click directive to call navNewPost() upon clicking the "New Post" navigation item. We will need to implement that in our AngularJS controller next:

app/assets/javascripts/Controllers/main/mainIndexCtrl.js.coffee

@IndexCtrl = ($scope, $location, $http, postData) ->

  # ...

  $scope.viewPost = (postId) ->
    $location.url('/post/'+postId)

  $scope.navNewPost = ->
    $location.url('/post/new')

@IndexCtrl.$inject = ['$scope', '$location', '$http', 'postData']


Just like with the viewPost method that we previously implemented, to implement this we simply leverage Angular's $location service to redirect us to the appropriate route. Now we have our blog homepage ready to accommodate the new post functionality. It should look something like this:

more...



Bootstrapping an AngularJS app in Rails 4.0 - Part 4

September 15, 2013 AngularJS Rails Tutorial

The full GitHub repository for this tutorial is available here

Introduction

This is part four of my tutorial covering building an Angular and Rails blog application from scratch. We will start where we left off in part 3. In the last post, we set up a simple Rails API and used our Angular controller to access that API on the client side. In this post I will cover:

  • Creating a shared AngularJS service to act as our model that:
    • Loads data from the Rails API on initial page load
    • Shares that data across all controllers
    • Does not require data to reload when switching pages

As before, this series assumes a certain basic understanding of both Rails and AngularJS. If you need an introduction to Rails, I recommend checking out the excellent Ruby on Rails Tutorial by Michael Hartl. For an intro to AngularJS, I recommend checking out the homepage tutorials and, to go a bit deeper, the excellent egghead.io tutorial videos by John Lindquist.


Setting up a shared AngularJS service as our model

First off, let's talk for a second about why we are choosing to use a shared service as the place where our model lives. An Angular service is a type of Angular object that is instantiated only once, no matter how many controllers or other objects inject it. This means that any Angular controller that injects this service will access the same instance, allowing for data to be easily shared across multiple controllers. This is not the only way for controllers to share or pass data in Angular. Other options include broadcasting messages on $rootScope or using global variables. But in my experience, shared services is easiest and the most scalable approach.

Setting up an Angular service is similar to setting up a controller or an application module. In keeping with the application structure we set up in part 1, create the new coffeescript file in the Services folder under main:

app/assets/javascripts/Services/main/postData.js.coffeescript

angular.module('Blog').factory('postData', ['$http', ($http) ->

  postData =
    data:
      posts: [{title: 'My first post', contents: 'Lorem ipsum dolor sit amet, consectetur adipiscing elit. Donec laoreet lobortis vulputate. Ut tempus, orci eu tempor sagittis, mauris orci ultrices arcu, in volutpat elit elit semper turpis. Maecenas id lorem quis magna lacinia tincidunt. In libero magna, pharetra in hendrerit vitae, luctus ac sem. Nulla velit augue, vestibulum a egestas et, imperdiet a lacus. Nam mi est, vulputate eu sollicitudin sed, convallis vel turpis. Cras interdum egestas turpis, ut vestibulum est placerat a. Proin quam tellus, cursus et aliquet ut, adipiscing id lacus. Aenean iaculis nulla justo.'}, {title: 'A walk down memory lane', contents: 'Lorem ipsum dolor sit amet, consectetur adipiscing elit. Proin leo sem, imperdiet in faucibus et, feugiat ultricies tellus. Vivamus pellentesque iaculis dolor, sed pellentesque est dignissim vitae. Donec euismod purus non metus condimentum porttitor suscipit nibh tempor. Etiam malesuada elit in lectus pharetra facilisis. Fusce at nisl augue. Donec at est felis. Sed a gravida diam. Nunc nunc mi, egestas non dignissim et, porta aliquam ante.'}]

  console.log("Initialized postData.")

  return postData

])


more...



Bootstrapping an AngularJS app in Rails 4.0 - Part 3

August 19, 2013 AngularJS Rails Tutorial

The full GitHub repository for this tutorial is available here

Introduction

This is part three of my tutorial covering building an Angular and Rails blog application from scratch. Jumping in again from where the last post left off, in this post I will cover:

  • Building a simple Rails API to serve blog post data
  • Connecting to that API using our main controller.

As before, this series assumes a certain basic understanding of both Rails and AngularJS. If you need an introduction to Rails, I recommend checking out the excellent Ruby on Rails Tutorial by Michael Hartl. For an intro to AngularJS, I recommend checking out the homepage tutorials and, to go a bit deeper, the excellent egghead.io tutorial videos by John Lindquist.


Creating a simple Rails model

To start with, we need a database model to store our blog data. As with our example data currently in our main AngularJS controller, we will keep this model simple. Each blog entry will have a title and will have its body stored in a contents field. We will also add fields for an author and a date. Luckily, Rails makes setting this model up simple. At the command line, use the Rails generate command to create the migration that sets up this model:


$ rails generate model Post title:string contents:text author:string post_date:datetime
      invoke  active_record
      create    db/migrate/20130803203410_create_posts.rb
      create    app/models/post.rb


As you can see, Rails generates our first database migration. If you open that migration up to inspect, it should look something like this.

db/migrate/[date-time-created]_create_posts.rb

class CreatePosts < ActiveRecord::Migration
  def change
    create_table :posts do |t|
      t.string :title
      t.text :contents
      t.string :author
      t.datetime :post_date

      t.timestamps
    end
  end
end


more...



Adding Bootstrap 3.0.0 WIP to your Rails app

July 18, 2013 Rails CSS

As I have begun to include Bootstrap 3.0.0 (and especially it's new responsive mobile framework) into my web application development, it has become clear that someone needs to DRY this process up. So I quickly built a simple gem to do this: Bootstrap-Rails-Three.

Version 3.0.0 of Bootstrap contains some really powerful new capabilities, as well as some good-looking updates to the CSS itself. That said, it should be noted that v.3.0.0 is a work in progress and is subject to bugs and/or breaking changes. It should be used in production apps at your own peril.

Installation

Installation is simple. Just add this line to your application's Gemfile:

more...



Bootstrapping an AngularJS app in Rails 4.0 - Part 2

June 23, 2013 AngularJS Rails Tutorial

The full GitHub repository for this tutorial is available here

Introduction

This is part two of my tutorial covering building an Angular and Rails blog application from scratch. Jumping off right from where the last part left off, in this post, I will cover:

  • Modularizing the AngularJS app
  • Setting up AngularJS routing
  • Using Angular's routing to manage multiple controllers and templates

As before, this series assumes a certain basic understanding of both Rails and AngularJS. If you need an introduction to Rails, I recommend checking out the excellent Ruby on Rails Tutorial by Michael Hartl. For an intro to AngularJS, I recommend checking out the homepage tutorials and, to go a bit deeper, the excellent egghead.io tutorial videos by John Lindquist.


Angular modules

The first thing we will do is create a module for our application. This module will allow us to leverage the ng-app directive to specify the main application module. Since this will be the master Angular module for the Main Rails controller, we will declare it up front in our main.js.coffee file:

app/assets/javascripts/main.js.coffee

# Place all the behaviors and hooks related to the matching controller here.
# All this logic will automatically be available in application.js.
# You can use CoffeeScript in this file: http://coffeescript.org/

#= require_self
#= require_tree ./Controllers/main
#= require_tree ./Directives/main
#= require_tree ./Filters/main
#= require_tree ./Services/main

# Creates new Angular module called 'Blog'
Blog = angular.module('Blog', [])


The next step is to specify the Blog module we just created as our main application module in the ng-app directive, which was declared in our opening <html> tag.

app/views/layouts/application.html.erb

<!DOCTYPE html>
<html ng-app="Blog">
<head>
  <title>Blog</title>
  <%= stylesheet_link_tag    "application", media: "all" %>
  <%= javascript_include_tag "application", controller_name %>
  <%= csrf_meta_tags %>
</head>
<body>

<%= yield %>

</body>
</html>


Even with this addition, not much has changed. The application is still declaring IndexCtrl to be the ng-controller and our Blog module does not have any functionality of its own. Let's change that by adding routing.

more...



Bootstrapping an AngularJS app in Rails 4.0 - Part 1

June 03, 2013 AngularJS Rails Tutorial

The full GitHub repository for this tutorial is available here

Introduction

I was in the process of building a blog for myself as an exercise to try out Rails 4.0. At the same time, I happened to be reading Rework, by Jason Fried and David Heinemeier Hansson. One of my favorite pieces of advice they gave was to focus not only on the main task of what you are doing, but also to recognize the byproducts. While I have a fair amount of experience with Rails and AngularJS, there is never a shortage of new things to learn. No matter how simple I keep this project, I will inevitably be learning as I go, so it seemed like the perfect opportunity to develop not only my new blog, but also some content.

I plan to focus these posts on:

  • Building a specific example from scratch, showing all my work along the way, and explaining what is going on at each step.

  • Demonstrating the ins and outs of using Rails on the back end together with AngularJS on the front end (which I believe to be an excellent pairing for many types of apps)

The scope of this exploration may expand as I go, but this is my current plan.

In this post, I will cover:

  • Creating a Rails 4.0 app
  • Adding AngularJS
  • Setting up the file structure for managing JS controllers, and
  • Implementing basic Rails and AngularJS controllers.

This series assumes a certain basic understanding of both Rails and AngularJS. If you need an introduction to Rails, I recommend checking out the excellent Ruby on Rails Tutorial by Michael Hartl. For an intro to AngularJS, I recommend checking out the homepage tutorials and, to go a bit deeper, the excellent egghead.io tutorial videos by John Lindquist.

So here we are. Let's see where this takes us.


Creating your Rails 4.0 app

Let's start by creating a Rails 4.0 application. (If you need help installing Ruby 2.0 or Rails 4.0 RC2, check out the "Up and Running" section of Michael Hartl's Ruby on Rails Tutorial.)

more...



AngularJS Cheatsheet

May 19, 2013 AngularJS

I found this great cheat sheet by ProLoser covering the basic AngularJS syntax. Given that there is still work to be done on the Angular docs, this could be a big time saver.

more...