我试图通过控制器调用工厂中定义的函数,但收到错误:
TypeError:undefined不是函数。
有人可以帮助我吗?
//service
angular.module('Blog').factory('postData', function($http) {
var postData = {}
postData.data.posts = [{
title: 'first title',
contents: 'first contents'
}]
postData.loadPosts = function() {
postData.data.posts = $http.get('./posts.json')
.success(function(data) {
postData.data.posts = data;
})
.error(function() {
console.error('Failed loading data');
})
}
postData.createPost = function(newPost) {
var data;
if (newPost.newPostTitle === '' || newPost.newPostContents === '') {
alert('Neither the Title nor the Body are allowed to be left blank.');
return false;
}
data = {
new_post: {
title: newPost.newPostTitle,
contents: newPost.newPostContents
}
};
$http.post('./posts.json', data).success(function(data) {
postData.data.posts.push(data);
console.log('Successfully created post.');
}).error(function() {
console.error('Failed to create new post.');
});
return true;
};
console.log("initialized postdata");
return postData;
})
//controller
var createPostCtrl = function($scope, $location, postData) {
postData = postData;
$scope.data = postData.data;
postData.loadPosts();
$scope.formData = {
newPostTitle: '',
newPostContents: ''
};
$scope.createPost = function() {
// This one is throwing an error TypeError: undefined is not a function
postData.createPost($scope.formData)
};
};
答案 0 :(得分:0)
模块函数需要依赖作为第二个参数。如果没有依赖,你可以写:
angular.module('Blog', [])