I am working with controllers and services in angular. It was my understanding that in the scenario of sharing date through a service between controllers that it is my responsibility to update the service since it doesn't have scope. I set a watch on the input fields and updated the service when the input changed. Why is the service in the other controller not getting updated? It is a singleton and has one instance..shouldn't the reference in the other controller be updated? The only solution I have found is to add a watch to listen for changes on the service and model but now I have two watch functions per controller to listen both ways. Is this correct? I feel that if I update the service the value should get updated in the other controller because everything is pointing to the same value.
https://jsfiddle.net/86hry8a5/
<div ng-controller="mainController as mainCtrl">
<div>
<input type="text" ng-model="mainCtrl.message" />
</div>
<div>
{{mainCtrl.message}}
</div>
</div>
<hr/>
<div ng-controller="secondController as secondCtrl">
<div>
<input type="text" ng-model="secondCtrl.message" />
</div>
<div>
{{secondCtrl.message}}
</div>
</div>
.controller('mainController', function(mainService, $scope){
var self = this;
self.message = mainService.message;
$scope.$watch(function(){return mainService.message}, function(){
self.message = mainService.message;
});
$scope.$watch(function(){return self.message}, function(){
mainService.message = self.message;
});
})
.controller('secondController', function(mainService, $scope){
var self = this;
self.message = mainService.message;
$scope.$watch(function(){return mainService.message}, function(){
self.message = mainService.message;
});
$scope.$watch(function(){return self.message}, function(){
mainService.message = self.message;
});
})
.service('mainService', function(){
var self = this;
self.message = 'service';
}
);