I have a scope binding to an array stored in a service. When the array changes, the scope notices the change and updates the values in my template.
However, when the Array gets replaced by another array, the scope doesn't seem to recognize a change and won't update the list.
I know that this is a common behaviour of angularjs and that it's probably intended to be like this, but I don't get why. In my understanding, the scope variable should update, whenever the bound reference changes.
Is $scope.myVar = anyOtherVar;
not equivalent to a $scope.$watch('anyOtherVar',function(..){//update myVar});
?
See my fiddle for demonstrating the problem. http://jsfiddle.net/sL9k7q9L/1/
var myApp = angular.module('myApp',[]);
//myApp.directive('myDirective', function() {});
myApp.factory('myService', function() {
var anyArray = [{"name":"peter"}];
var anyOtherArray = [{"name":"laura"}];
return {
anyArray: anyArray,
newElement: function(){
anyArray.push({"name":"bob"});
},
replaceWholeArray: function(){
anyArray = anyOtherArray;
console.log(anyArray);
}
}
});
function MyCtrl($scope,myService) {
$scope.elements = myService.anyArray;
$scope.newElement = function(){
myService.newElement();
}
$scope.replaceWholeArray = function(){
myService.replaceWholeArray();
}
}
and the corresponding template:
<div ng-controller="MyCtrl">
<button ng-click="newElement()">
newElement()
</button>
<button ng-click="replaceWholeArray()">
replaceWholeArray()
</button>
<ul>
<li ng-repeat="el in elements">{{el.name}}</li>
</ul>
</div>
You are updating variables but that doesn't update any other variable assignments that were made using the original variable.
Thus reference to original array is broken for myService.anyArray
Simple example
var a = 1;
var b = a;
a = 2;
alert(b);// is still 1 due to value of `a` when it was assigned
Instead just update the factory object property but to do that you need to store a reference to the returned object first
myApp.factory('myService', function() {
var anyArray = [...];
var anyOtherArray = [...];
var factoryObject = {
anyArray: anyArray,
newElement: function() {
anyArray.push({"name": "bob"});
},
replaceWholeArray: function() {
// change this part
//anyArray = anyOtherArray;
// To:
factoryObject.anyArray = anyOtherArray;
}
}
return factoryObject
});