I have established a service to facilitate the sharing of data/state across multiple controllers. One of the controllers updates certain properties within the service using scope data through a save function. The updated data is then accessed by other controllers by assigning a scope value to the service. However, I have encountered an issue wherein the behavior varies depending on whether the data assigned from the first controller to the service is a primitive value or an object. If it's a primitive value, the service's property only updates upon execution of the save function. On the other hand, if it's an object, the service continues to update as the model data changes. I am seeking to implement a "save" functionality and would like to understand why objects are immediately updated and how to properly handle object updates through the save function.
I am trying to comprehend the differences in behavior between primitives and objects, along with why objects update instantaneously. Additionally, I am exploring the best approach to implementing the save function with objects. While I am aware of utilizing events such as broadcasting an event on $rootScope and listening for it in the second controller to assign the service property to a scope variable, I prefer the simplicity of directly assigning the service to the scope in the second controller and would like to explore this method further if feasible.
Below 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;
}]);
In the view (partial):
<div ng-controller="OutputCtrl">
<strong>Text:</strong> {{ myService.text }}<br>
<strong>Obj Text:</strong> {{ myService.objText }}
</div>
For a complete demonstration, visit: http://jsfiddle.net/anpsince83/uRH93/2/