I am puzzled by the behavior of the code snippet below, as it only produces the following output:
Array []
Array [object, object]
Instead, when submitting the form, I anticipate the output to be:
Array [object, object]
Array [object, object]
You can view the code here.
Why does the line
$scope.posts.push({
title: $scope.title,
link: $scope.link,
upvotes: 0
});
not immediately update the service?
Any insights would be greatly appreciated. Thank you.
angular.module('flapperNews', [])
.factory('postsFactory', [function(){
// Modularize posts frontend storage for better mock testing and independency of scope
var posts_factory_object = {
posts_list: []
};
return posts_factory_object;
}])
.controller('MainCtrl', [
'$scope',
'postsFactory',
function($scope, postsFactory){
// Bind scope.posts to postsFactory.posts_list
$scope.posts = postsFactory.posts_list;
// Variable pseudo post data for test
$scope.posts = [
{title: 'post 1', upvotes: 5},
];
// Frontend function for keeping track of state purely in frontend
$scope.addPost = function(){
// Check if inputted string is undefinied or empty
if (!$scope.title || $scope.title ===''){ return; }
$scope.posts.push({
title: $scope.title,
link: $scope.link,
upvotes: 0
});
$scope.title = '';
$scope.link = '';
console.log(postsFactory.posts_list);
console.log($scope.posts);
};
}]);