Skip to content

Instantly share code, notes, and snippets.

@jgroeneveld
Last active August 29, 2015 14:02
Show Gist options
  • Save jgroeneveld/2bd1a6b19edd1d716b72 to your computer and use it in GitHub Desktop.
Save jgroeneveld/2bd1a6b19edd1d716b72 to your computer and use it in GitHub Desktop.
Rails & AngularJS

This is a description on how to add AngularJS to a Rails App.

  • Put the angular javascript files into assets/javascripts/lib/angular-xxx

  • Add the libs to an index file (if you are not using anything else, application.js)

  • Add your apps dependencies to the same file

          # app/assets/javascripts/application.js.coffee
          #= require lib/angular-xxx/angular
          #= require lib/angular-xxx/angular-route
          #= require app/main
          #= require app/routes
          #= require_tree ./app/controllers
          #= require_tree ./app/services
    
  • load your app in your main file

          # app/assets/javascripts/app/main.js.coffee
          @app = angular.module("myApp", ['ngRoute'])
    
  • Add the routes

          # app/assets/javascripts/app/routes.js.coffee
          #= depend_on_asset "app/templates/home.html"
          
          @app.config(['$routeProvider', ($routeProvider) ->
            $routeProvider.otherwise({
              templateUrl: '<%= asset_path("app/templates/home.html") %>',
              controller: "HomeController"
            })
          ])
    
  • Add an initializer to allow your Template Engine to render the templates

          # config/initializers/assets_slim_template.rb
          Rails.application.assets.register_engine('.slim', Slim::Template)
    
  • Add controllers

          # app/assets/javascripts/app/controllers/home_controller.js.coffee
          class HomeController
            @$inject = ["$scope"]
            constructor: ($scope) ->
              $scope.message = "Hello World"
          
          @app.controller "HomeController", HomeController
    
  • Add templates

          # app/assets/javascripts/app/templates/home.html.slim
          Message: {{ message }}
    
  • etc.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment