I use the service to exchange data between controllers. The application should update the DOM when the variable changes. I found two ways to do this, you can see the code here:
http://jsfiddle.net/sosegon/9x4N3/7/
myApp.controller( "ctrl1", [ "$scope", "myService", function( $scope, myService ){ $scope.init = function(){ $scope.myVariable = myService.myVariable; }; }]);
myApp.controller( "ctrl2", [ "$scope", "myService", function( $scope, myService ){ $scope.increaseVal = function(){ var a = myService.myVariable.value; myService.myVariable.value = a + 1; }; }]);
http://jsfiddle.net/sosegon/Y93Wn/3/
myApp.controller( "ctrl1", [ "$scope", "myService", function( $scope, myService ){ $scope.init = function(){ $scope.increasedCounter = 1; $scope.myVariable = myService.myVariable; }; $scope.$on( "increased", function(){ $scope.increasedCounter += 1; } }]);
myApp.controller( "ctrl2", [ "$scope", "myService", function( $scope, myService ){ $scope.increaseVal = function(){ myService.increaseVal(); }; }]);
In the first case, I pass a variable from a service with a controller and $ look at it in a directive. Here I can change the variable directly in this controller or any other controller that uses it, and the DOM is updated.
In another option, I use a function from a service to change the variable that passed the event. This event is listened by the controller, then the DOM is updated.
I would like to know which option is better, and the reasons for this.
Thanks.
EDIT:
The code in jsFiddle is a simplified version of real code that has more objects and functions. In a service, the myVariable value field is actually an object with much more information than just a primitive type; this information should be displayed and updated in the DOM. The myVariable.value object is set in every change:
myVariable.value = newValue;
When this happens, all DOM elements should be updated. Since the information contained in myVariable.value is variable, the number of property changes (I cannot use an array), it is much easier to delete DOM elements and create new ones, which I do in the directive (but with a lot of elements in real code):
scope.$watch( "myVariable.value", function( newVal, oldVal ){ if( newVal === oldVal ){ return; } while( element[0].children.length > 0 ){ element[0].removeChild( element[0].firstChild ); } var e = angular.element( element ); e.append( "<span>Value is: " + scope.myVariable.value + "</span>" ); } );