【发布时间】:2015-05-04 18:23:20
【问题描述】:
我正在通过本教程 https://thinkster.io/angulartutorial/angular-rails/ 学习如何将 Angularjs 与 ROR 一起使用
当我为一项服务添加一个新功能时,我正处于这样一个时刻,该服务应该获取我在数据库中的所有帖子。但是,当我运行代码时,页面不再加载,并且我的服务器日志中没有数据库调用。在进行此更改之前,一切正常。如果有人可以看看它,那就太好了。请注意,我的 Rails 路由返回 json 就好了。
app.js
angular.module('flapperNews', ['ui.router', 'templates'])
.config([
'$stateProvider',
'$urlRouterProvider',
function($stateProvider, $urlRouterProvider) {
$stateProvider
.state('home', {
url: '/home',
templateUrl: 'home/_home.html',
controller: 'MainCtrl',
resolve: {
postPromise: ['posts', function(posts){
return posts.getAll();
}]
}
})
.state('posts', {
url: '/posts/{id}',
templateUrl: 'posts/_posts.html',
controller: 'PostsCtrl'
});
$urlRouterProvider.otherwise('home');
}]);
posts/posts.js
angular.module('flapperNews')
.factory('posts', [
'http',
function($http){
var o = {
posts: []
};
o.getAll = function() {
return $http.get('/posts.json').success(function(data){
angular.copy(data, o.posts);
});
};
return o;
}]);
posts/postsCtrl.js
angular.module('flapperNews')
.controller('PostsCtrl', [
'$scope',
'$stateParams',
'posts',
function($scope, $stateParams, posts){
$scope.post = posts.posts[$stateParams.id];
$scope.addComment = function(){
if($scope.body === '') { return; }
$scope.post.comments.push({
body: $scope.body,
author: 'user',
upvotes: 0
});
$scope.body = '';
};
}]);
home/mainCtrl.js
angular.module('flapperNews')
.controller('MainCtrl', [
'$scope',
'posts',
function($scope, posts){
$scope.posts = posts.posts;
$scope.addPost = function(){
if(!$scope.title || $scope.title === '') { return; }
$scope.posts.push({
title: $scope.title,
link: $scope.link,
upvotes: 0,
comments: [
{author: 'Joe', body: 'Cool post!', upvotes: 0},
{author: 'Bob', body: 'Great idea but everything is wrong!', upvotes: 0}
]
});
$scope.title = '';
$scope.link = '';
};
$scope.incrementUpvotes = function(post) {
post.upvotes += 1;
}
}]);
【问题讨论】:
标签: html ruby-on-rails angularjs