我正在尝试在我的控制器中注入工厂。
var app = angular.module('BlogApp', ['ngMaterial']);
app.factory("Post", function ($resource) {
return $resource("/rest/admin/search/posts");
});
app.controller('postController', ['$scope', function ($scope, Post) {
$scope.getPost = Post.get({id: 1}, function (data) {
//do something
});
}
]);
始终会收到与Post未定义相同的错误,"无法读取属性' get'未定义" 我做错了什么?提前谢谢!
答案 0 :(得分:5)
在缩小angularjs代码时错过了所需的参数:
app.controller('postController', ['$scope', function ($scope, Post) {
$scope.getPost = Post.get({id: 1}, function (data) {
//do something
});
}
成为:
app.controller('postController', ['$scope', 'Post', function ($scope, Post) {
$scope.getPost = Post.get({id: 1}, function (data) {
//do something
});
}
答案 1 :(得分:2)
您没有在依赖项列表中列出Post
。只需添加它:
app.controller('postController', ['$scope', 'Post', function ($scope, Post) { /* ... */ }]);
答案 2 :(得分:1)
将 ngResource 依赖项注入您的模块:
var app = angular.module('BlogApp', ['ngMaterial', 'ngResource']);
并将发布工厂注入控制器:
app.controller('postController', ['$scope', 'Post' function ($scope, Post) {
$scope.getPost = Post.get({id: 1}, function (data) {
//do something
});
}]);
希望它有所帮助。