I have created rails view (ERB). However, I want to integrate it into angularjs $routeProvider
, but I don\'t know what url should I fill into templateUrl<
Angular js provides its own routes. rails routes will always be used when you want to connect your views with database(CRUD). that is data binding with angular.js now i will show you how to use it with rails...
I want to add new user using angular js views and list all users. i will use rails as backend to store users in database so i will create user_controller
First Create resource of user. we will not create any views so be carefull for that
rails g resource user name:string
Then go to route.rb and check there is a route created, and create Home controller with index action that we will use as our single page application where our output will be yield.
rails g controller home index
root to: "home#index"
type this command on terminal where you will see our 7 routes. we never use new and edit method, because new and edit don't respond to json.
rake routes
Now we want all user with a unique name so go to create_user migration and uncomment this line and then we will migrate the database.
add_index :users, :name, unique: true
rake db:migrate
Now modify our controller so that all data fetching and insertion will be done with json format. so put this code inside users_controller.rb, if you are using rails 4 then follow this otherwise not. attributes will be adjustable in 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
Its time to use angulajs in our rails application
Go to application.html.erb replace tag line with this
Now add angular.js file in asses/javascripts, download it from http://angularjs.org/
Now we will create a controller to handle our angular application routes to know then that this controller wants something from me. so type this on terminal
mkdir -p app/assets/javascripts/angular/controllers
Now let's create the controller file itself. I'm calling this controller the "userCtrl", Thus our filename will be app/assets/javascripts/angular/controllers/userCtrl.js.coffee
In controller userCtrl
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 insert new user record into database, by creating createUser method)
Create a view for taking input from user write this code in home/index.html.erb.
All users
{{c.name}}
Run application and watch output.