$scope.$watch issue in ng-1.1.x
by DotDotDot
HTML
<div ng-controller="CtrlA">
<h1>Things in CtrlA:</h1>
<ul>
<li ng-repeat="thing in getThings()">{{thing}}</li>
</ul>
</div>
<div ng-controller="CtrlB">
<h1>Things in CtrlB:</h1>
<ul>
<li ng-repeat="thing in getThings()">{{thing}}</li>
</ul>
</div>
JavaScript
(function () {
angular.module('testApp', [])
.factory('TestService', function ($http) {
var service = {
things: [],
setThings: function (newThings) {
service.things = newThings;
},
getThings:function(){
return service.things;
}
};
return service;
})
.controller('CtrlA', function ($scope, $timeout, TestService) {
$scope.things = TestService.getThings();
$scope.getThings=function(){return TestService.getThings();};
$scope.$watch('getThings()', function (n, o) {
if (n !== o) {
// never alerts
alert('Things have changed in CtrlA');
}
}, true);
$timeout(function () {
TestService.setThings(['a', 'b', 'c']);
// Without the next line, CtrlA acts like CtrlB in that
// it's $scope.things doesn't receive an update
$scope.things = TestService.things;
}, 2000);
})
.controller('CtrlB', function ($scope, TestService, $timeout) {
$scope.things = TestService.getThings();
$scope.getThings=function(){return TestService.getThings();};
$scope.$watch('getThings()', function (n, o) {
if (n !== o) {
// never alerts
alert('Things have changed in CtrlB');
}
}, true);
})
})();