I simplified my actual code but the problem is the same. After you click Start counter
anonymous function in "First controller" starts changing data inside myService
. First it works ok. But after switching to "Second controller" Angular stops auto-updating value of <span ng-bind="getData().data">
even if you navigate back to "First controller".
However if you switch controllers back and forth a bit you can see that span is updating on controller load so data is changing and controllers can access it. It's just Angular not auto-tracking it anymore.
How can I make Angular to start tracking changes and update element after switching controllers again?
<html>
<head>
<script src="https://code.angularjs.org/1.4.0-beta.4/angular.min.js"></script>
<script src="https://code.angularjs.org/1.4.0-beta.4/angular-route.min.js"></script>
</head>
<body>
<div style="padding: 0 0 20px 0">
<a href="#/first">First controller</a> | <a href="#/second">Second controller</a>
</div>
<div ng-app="myApp">
<div ng-view></div>
<script type="text/ng-template" id="temp1.html">
Data: <span ng-bind="getData().data"></span>
<br/>
<button ng-click="start()">Start counter</button>
</script>
<script type="text/ng-template" id="temp2.html">
Data: <span ng-bind="getData().data"></span>
</script>
</div>
<script type="text/javascript">
var myControllers = angular.module('myControllers', []);
myControllers.factory('myService', [function() {
return { data: 0 };
}]);
myControllers.controller('myController1', ['$scope', 'myService', function($scope, myService){
$scope.getData = function() {
return myService;
}
$scope.start = function() {
setInterval(function() {
myService.data++;
$scope.$apply();
}, 1000)
}
}]);
myControllers.controller('myController2', ['$scope', 'myService', function($scope, myService){
$scope.getData = function() {
return myService;
}
}]);
var myApp = angular.module('myApp', [
'ngRoute',
'myControllers'
]);
myApp.config(['$routeProvider',function($routeProvider) {
$routeProvider.
when("/first",{ controller: "myController1", templateUrl: "temp1.html"}).
when("/second", {controller: "myController2", templateUrl: "temp2.html"}).
otherwise({redirectTo : "/first"});
}]);
</script>
</body>
</html>