Friday, 23 August 2013

$watch a service variable or $broadcast an event with AngularJS

$watch a service variable or $broadcast an event with AngularJS

I'm using a service to share data between controllers. The application has
to update the DOM when a variable is modified. I've found two ways to do
that, 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 share a variable from the service with the controller
and $watch it in the directive. Here, I can modify the variable directly
in this controller, or any other controller that share it, and the DOM is
updated.
In the other option, I use a function from the service to modify the
variable which $broadcast an event. That event is listened by the
controller, then the DOM is updated.
I'd like to know which option is better and the reasons for that.
Thanks.

No comments:

Post a Comment