Setup Angular in a Rails 4 App

Use angular in a rails app

First we create the rails app

rails new awesome_app -d postgresql

Now some initial setup. Change directories to your app.

cd awesome_app

Gemfile

1
2
  gem 'bower-rails'
  gem 'angular-rails-templates'

Lets create a quick scaffold for posts

rails g scaffold posts title:string content:text

Then lets create and rake our database.

rake db:create

rake db:migrate

And lets install our gems

bundle

Once finished we can initialize bower

rails g bower_rails:initialize json

bower.js

1
2
3
4
5
6
7
8
9
{
    "lib": {
        "name": "bower-rails generated lib assets",
        "dependencies": {
            "angular": "latest",
            "angular-route": "latest"
        }
    }
}

and now lets install our dependencies

rake bower:install

We can can now start setting up our assets. Open app/assets/javascripts/application.js remove this line

1
  //= require turbolinks

and add the following

1
2
3
4
  //= require angular
  //= require angular-route
  //= require angular-rails-templates
  //= require_tree ../templates

Now you will notice we added a ../templates require. We need to create this. From the root of the rails app run

mkdir app/assets/templates

config/routes.rb

1
2
3
4
5
6
7
  Rails.application.routes.draw do

      root 'posts#index'
      get '*' => 'posts#index'
      resources :posts

  end

Now open the app/views/layouts.application.html.haml and add to the body tag

1
  %body{"ng-app"=>"AngularAwesome"}

this will initialize our angular application.

app/assets/javascripts/ng-app/app.js

1
2
3
4
5
6
7
8
9
10
11
12
  angular
    .module('AngularAwesome', [
        'ngRoute',
        'templates'
    ]).config(function ($routeProvider, $locationProvider) {
        $routeProvider
            .when('/', {
                templateUrl: 'home.html',
                controller: 'HomeCtrl'
            });
        $locationProvider.html5Mode(true);
    });

app/assets/javascripts/ng-app/controllers/home.js

1
2
3
4
5
6
  angular.module('AngularAwesome')
    .controller('HomeCtrl', function ($scope) {
        $scope.hello = function(){
          alert('hello world');
        };
    });

app/assets/templates/index.html.haml

1
2
3
  %h1 Lets say hello!
  %button{'ng-click' => "hello()"}
    Say Hello

And we will want to set the root of our application

1
  %base{:href => "/"}/

Now when we hit the root of our application and click our button we will get an alert of hello world.