Angular js provides its own routes. route routes will always be used when you want to connect your views to a database (CRUD). this is data binding using angular.js, now i will show you how to use it with rails ...
I want to add a new user using angular js views and a list of all users. I will use rails as a backend to store users in the database, so I will create user_controller
First create a user resource. we will not create any views, so be careful for this
rails g resource user name:string
Then go to route.rb and check if the created route exists, and create a Home controller with an index action, which we will use as our application for one page where our output will work.
rails g controller home index root to: "home#index"
enter this command on the terminal where you will see our 7 routes. we never use a new and editable method because new and edit do not respond to json.
rake routes
Now we want all users with a unique name go to create_user migration and uncomment this line, and then we transfer the database.
add_index :users, :name, unique: true rake db:migrate
Now change our controller so that all fetching and data insertion are done using json format. so put this code inside users_controller.rb if you are using rails 4 then follow this otherwise. attributes will be adjusted in the model.
class UsersController < ApplicationController respond_to :json def index respond_with User.all end def create respond_with User.create(user_params) end private def user_params params.require(:user).permit(:name) end end
Angulajs usage time in our rails app
Go to application.html.erb replace the tag string with this
<html ng-app="userApp">
Now add the angular.js file to asses / javascripts, download it from http://angularjs.org/
Now we will create a controller to handle our angular application routes to know that this controller wants something from me. so enter this on the terminal
mkdir -p app/assets/javascripts/angular/controllers
Now create the controller file itself. I call this controller "userCtrl". So our name will be Application / Assets / JavaScripts / angular / controllers / userCtrl.js.coffee
In userCtrl controller
app = angular.module("userApp", ["ngResource"]) @userCtrl = ($scope, $resource) -> User = $resource("/users", {id: "@id"}, {update: {method: "PUT"}}) $scope.users = User.query() $scope.createUser = -> user = User.save($scope.newUser) $scope.users.push(user)
(This will add a new user record to the database by creating the createUser method)
Create a view to enter user input, write this code in home / index.html.erb.
<div ng-controller="userCtrl"> <form ng-submit="createUser()"> <label>Enter Name</label> <input type="text" placeholder="Enter user name" ng-model="newUser.name" /> <button ng-click="createUser()" class="button tiny">Submit</button> </form> <h4 ng-show="users.$resolved && users.length > 1">All users</h4> <span ng-repeat="c in users"> {{c.name}}<br> </span> </div>
Launch the application and view the clock.
source share