Edward G. Edward G. - 7 months ago 11
Javascript Question

Why I keep getting TypeError setting property of undefined in angularJS?

I'm writing a microblog app to teach myself angularJS.

Now an annoying problem is that I'm so messed up with service, factory and provider.
After searching for the differences between them I choose service to fullfill the part of making post in my app.

But then I keep getting the error: TypeError: Cannot set property 'get' of undefined

My service code looks like:

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);
};
});


And in my controller I wrote something like:

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();
}
]);


Any good practice are appreciated. :).




The problem sucks me so hard.I'm really tired of it.Tried to make it simple to find out where the error comes from and rewrite my code into a html file as follow:

<!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>


and the error goes like:


TypeError: Cannot call method 'get' of undefined

Answer

Change the service code to:

app.service('posts', function () {
    var posts = [];
    return {
        get: function () {
            return posts
        },
        push: function (user, text) {
            posts.push({
                user: user,
                text: text
            });
        }
    };
});

And the module are injected in order, you missed '$scope' so the module injection doesn't match.

app.controller('makePostCtrl', ['$scope', 'posts', function ($scope, posts) {
Comments