What is AngularJS?
Rails 3 and AngularJS – a small tutorial
First of all, create a new Rails app, and change your html-tag to
You have to intercept html requests to create a single-page application. If you have your root (eg: home#index) you can easily put a before_filter in your ApplicationController to render ‘home/index‘ or even another layout every time the request format is HTML.
I recommend to read the conceptual overview. Understand Angular’s vocabulary and how all the Angular components work together. Watch the AngularJS Tutorial (with node.js). It explains every major AngularJS feature and also gives a live demo.
Create a new JS File (or use your application.js) and try creating your first AngularJS controller.
The data is now hardcoded in the controller, later $scope.shows will be defined with data from an external API. (you can also use rails routes and respond_to :json if you use Rails Models)
As you see, you can define one part of your site to use AngularJS – and you can make many separated controllers.
To load real data by ajax call, you need to add $http in your controller function:
Add a module
For example, you would like to add localstorage functionality to your angular app. First look for an angular module, before you write one by yourself ;) –> github.com/grevory/angular-local-storage
Now it’s time to define your own app (appname) and add this module (LocalStorageModule). You can add as many modules as you like. In ‘LocalStorageModule’ a service called ‘localStorageService’ is defined. To use this service you have to include it in your controller initialization next to $scope and $http.
Last step: update the html-tag and define the app name. Now you can use ‘localStorageService’ in your controller.
Below are some code snippets with examples how to use it (in comments above every function).
There can be a minification problem if you use Rails with AngularJS (the Rails Asset Pipeline minifies all asset files). I got an error when deploying on heroku:
Uncaught Error: Unknown provider: e
before I did this: (not wrong, but leads to an error!)
According to AngularJS tutorial (docs.angularjs.org/tutorial/step_05) you can change this line to the following to prevent minification issues:
I hope I’ve helped some of you to get started with AngularJS and Rails.