I've just been starting on AngularJS and I'm still trying to understand creating services. From this and this, my understanding is as long as changes to variables are within Angular, there is no need to $watch them. I copied code from here, and modified it to see if I can get my first service to work:
myApp.factory('ListService', function() {
var ListService = {};
var list = ['a', 'b', 'c'];
ListService.addItem = function(item) { list.push(item); }
ListService.size = function() { return list.length; }
ListService.size1 = list.length;
return ListService;
});
function Ctrl1($scope, ListService) {
$scope.message = ListService.size();
$scope.addItem = function(){
ListService.addItem('d');
console.log("size() is " + ListService.size());
console.log("size1 is " + ListService.size1);
}
}
function Ctrl2($scope, ListService) {
$scope.message = ListService.size1;
}
The html is simply:
<div ng-controller="Ctrl1"> Count is: {{ message }}
<input type="button" ng-click="addItem">
</div>
<div ng-controller="Ctrl2"> Count is: {{ message }}
</div>
When clicking the button, the console log shows the correct counts, but "messages" remain the same. The original code is supposed to be contrived and was meant to show that services could be used to share code across controllers.
So my questions is, why isn't this working? I apologize if I missed something very simple. I'm a beginner and I'm still trying to get a hang of things.
Instead
$scope.message = ListService.size();
try
$scope.getCount = function () {
return ListService.size();
};
and then in view:
Count is: {{getCount()}}
It is because your $scope.message is primitive value that contains ListService's size at the moment of controller initialization.
(I'm realy bad in English speaking, so sorry for short answer).