I'm new to angularjs/clientjs and would like to consume a rails json api with angularjs. After some research I wrote the ff: code but when I visit http://localhost:3000/users
I get plain json. Angularjs is not being called to render a view.
How can I render an angularjs view that formats and shows the data a rails json api returns?
rails/routes
app::Application.routes.draw do
get 'main/index' => 'main#index'
resources :users, defaults: {format: :json}
end
rails/users_controller.rb
def index
@users = User.all
end
rails/main_controller.rb
def index
# blank
end
rails/application layout
..
<html ng-app='gold'>
..
<div ng-view>
<%= yield %>
</div>
..
app/assets/templates/main/index.html
app/assets/templates/users/index.html
app/assets/javascripts/main.js
var myApp = angular.module('gold', ['ngRoute', 'ngResource']);
myApp.config(function($routeProvider, $locationProvider, $httpProvider) {
console.log("in router")
$httpProvider.defaults.headers.common['X-CSRF-Token'] =
$('meta[name=csrf-token]').attr('content');
$locationProvider.html5Mode(true);
$routeProvider.
when('/users', {
templateUrl: '../assets/users/index.html',
controller: 'UsersController'
}).when('/main/index', {
templateUrl: '../assets/main/index.html',
controller: 'MainController'
}).otherwise({
redirectTo: '/'
});
});
app/assets/javascripts/services/UserService.js
myApp.factory('UserService', ['$resource', function($resource) {
console.log("in user service")
return $resource('/users/:id', {id: '@id'}, {
index: { method: 'GET', isArray: true },
create: { method: 'POST' },
show: { method: 'GET' },
update: { method: 'PUT', params: {id: '@id'} }
//delete: { method: 'DELETE', params: {id: '@id'} }
});
}]);
app/assets/javascripts/controllers/UsersController.js
myApp.controller('UsersController', ['$scope', 'UserService', function($scope, UserService) {
console.log("in user controller")
$scope.users = UserService.query();
}]);