How To Keep Service Data The Same On Multiple Controllers Without Using $watch?
There's an older answer I saw here on S.O, which states: 'This JavaScript works as we are passing an object back from the service rather than a value. When a JavaScript object
Solution 1:
In your second controller, you're storing the value of count
directly, which makes a copy of count at the time it was assigned. If count were an object, then {{service.count}}
and $scope.count
would just be a reference to the same object. Then modified properties of the object would be synchronized between controllers.
Eg.
//in DemoService
self.count = {value: 0};
// Binding in html for controller 1
{{service.count.value}}
// Assignment in controller 2:
$scope.count = DemoService.count;
//$scope.count.value === controller1.service.count.value === 0
service.count.value += 100
//$scope.count.value === controller1.service.count.value === 100
Note that Angular may not pick up on the changes to the object until the next full digest cycle.
Post a Comment for "How To Keep Service Data The Same On Multiple Controllers Without Using $watch?"