I've set up a service to share some data/state between multiple controllers. In one controller, I update some of the service properties with scope data through a save function. That data is then used in the other controllers by assigning a scope value to the service. The problem is, depending on the type of data that the first controller assigns to the service, their is different behavior. If the model data is a primitive value then the service's property will ONLY be updated when the save function is ran. However, if the model data is an object, it will continue to update the service as the model data is changed. I'm looking to implement "save" functionality, so this is not what I'm looking for.
So I'm trying to understand the different behavior: primitive vs. object and why the object updates immediately and also, what would be the proper way to implement the save function with the object. I'm aware you can use events and I could $broadcast and event on $rootScope and use that event on the second controller to assign the service property to a scope var, but I like the simplicity of assigning the service to the scope in the second controller and would like to use that method if possible.
Here is a simplified example.
var myApp = angular.module('myApp', []);
myApp.service('myService', function () {
this.text = '';
this.objText = {};
this.setText = function (text) {
this.text = text;
};
this.setObjText = function (obj) {
this.objText = obj;
};
});
myApp.controller('InputCtrl', ['$scope', 'myService', function ($scope, myService) {
$scope.textObj = {};
$scope.saveText = function (text) {
myService.setText(text);
}
$scope.saveObj = function (obj) {
myService.setObjText(obj);
}
}]);
myApp.controller('OutputCtrl', ['$scope', 'myService', function ($scope, myService) {
$scope.myService = myService;
}]);
And in the view (partial):
<div ng-controller="OutputCtrl">
<strong>Text:</strong> {{ myService.text }}<br>
<strong>Obj Text:</strong> {{ myService.objText }
</div>
Complete fiddle here: http://jsfiddle.net/anpsince83/uRH93/2/