[英]Why I keep getting TypeError setting property of undefined in angularJS?
我正在写一个微博客应用程序来教自己angularJS。
现在,一个令人烦恼的问题是,我对服务,工厂和提供者非常困惑。 在找到它们之间的差异之后,我选择了服务来填补我应用中发布帖子的部分。
但是然后我继续收到错误消息:TypeError:无法设置未定义的属性“ get”
我的服务代码如下:
angular.module('mblogApp.services',[]).
service('Posts', function(){
var posts = [];
this.prototype.get = function(){return posts};
this.prototype.push = function(user, text){
var post = {
user: user,
text: text,
time: Date.now()
};
posts.push(post);
};
});
在我的控制器中,我写了类似以下内容:
angular.module('mblogApp.controllers').
controller('makePostCtrl', ['Posts', function($scope, Posts){
posts.push($scope.user, $scope.text);
}]).
controller('showPostCtrl', ['Posts', function($scope, Posts){
$scope.posts = Posts.get();
}
]);
任何良好的做法表示赞赏。 :)。
这个问题让我很难受。我真的很累了。试图简化查找错误的根源并将我的代码重写为html文件,如下所示:
<!DOCTYPE html>
<html ng-app="app">
<head>
<title>Angular Service Demo</title>
<script type="text/javascript" src="angular/angular.js"></script>
</head>
<body>
<div ng-controller="makePostCtrl">
<label for="name">Name: </label>
<input type="text" ng-model="name">
<br>
<label for="text">Text: </label>
<input type="text" ng-model="text">
<br>
<button ng-click="post()">post</button>
</div>
<div ng-controller="showPostCtrl">
<ul>
<li ng-repeat="post in posts">
<p>Name: {{post.name}}</p>
<p>Text: {{post.text}}</p>
</li>
</ul>
</div>
</body>
<script type="text/javascript">
var app = angular.module('app', []);
app.service('posts', function(){
this.posts = function(){
var posts = [];
return {
get: function(){return posts},
push: function(user, text){
posts.push({
user: user,
text: text
});
}
};
};
});
app.controller('makePostCtrl ', ['posts',function($scope, posts){
$scope.post = function(){
posts.push($scope.user, $scope.text);
};
$scope.posts = posts.get();
}]);
app.controller('showPostCtrl')
</script>
</html>
错误如下:
TypeError:无法调用未定义的方法“ get”
将服务代码更改为:
app.service('posts', function () {
var posts = [];
return {
get: function () {
return posts
},
push: function (user, text) {
posts.push({
user: user,
text: text
});
}
};
});
然后按顺序注入模块,您错过了“ $ scope”,因此模块注入不匹配。
app.controller('makePostCtrl', ['$scope', 'posts', function ($scope, posts) {
我相信您缺少服务的依赖项注入。 尝试这个
angular.module('mblogApp.controllers',['mblogApp.services']).
试试这个代码。
为您服务,做出这样的改变;
angular.module('mblogApp'). service('Posts', function(){
var post_values = [];
return {
get : function(){
return post_values
},
push : function(user, text){
var post = {
user: user,
text: text,
time: Date.now()
};
post_values.push(post);
}
};
});
还有你的控制器;
var app = angular.module('mblogApp');
app.controller('makePostCtrl', ['Posts', function ($scope, Posts) {
Posts.push($scope.user, $scope.text);
});
app.controller('showPostCtrl', ['Posts', function ($scope, Posts) {
$scope.posts = Posts.get();
});
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.