I was going through the Thinkster.io MEAN Stack tutorial and had a question about why my implementation doesn't work. I know this isn't what is exactly being asked but was wondering how you would make this work. I wanted to use the factory to show my posts that I moved into my factory from the controller. The code is shown below for app.js.
`
var app = angular.module('flapperNews', []);
app.factory('posts', [function(){
var o = {posts:[{title: 'post 1', upvotes: 5}, {title: 'post 2', upvotes: 2}, {title: 'post 3', upvotes: 15}, {title: 'post 4', upvotes: 9},{title: 'post 5', upvotes: 4}];
};
return o;
}]);
app.controller('MainCtrl', ['$scope', 'posts',function($scope, posts){
$scope.test = 'Hello world!';
$scope.posts = posts.posts;
$scope.addPost = function(){
if(!$scope.title || $scope.title === ''){
return;
}
$scope.posts.push({title: $scope.title, link: $scope.link, upvotes: 0});
$scope.title = '';
$scope.link = '';
};
$scope.incrementUpvotes = function(post){
post.upvotes += 1;
};
}]);
`
Originally the object of posts in the factory was in the controller as $scope.posts. Now it is in the factory (being referenced as posts.posts) and does not display. How would you make the array display in the html, as I have {{post.title}} under a main controller div with ng-repeat that works prior to the factory being introduced.
Your JSON data is not formatted properly. There is a semi-colon inside your JSON data after the array posts
.
Use this and it should work:
var o = {
posts: [{
title: 'post 1',
upvotes: 5
}, {
title: 'post 2',
upvotes: 2
}, {
title: 'post 3',
upvotes: 15
}, {
title: 'post 4',
upvotes: 9
}, {
title: 'post 5',
upvotes: 4
}]
};