0

So I have a controller watching for changes from several different services that are injected into it. The controller is currently inheriting each of the service's scope to $watch one value from it. I would love to find a way to $watch that one value without dragging the services entire scope into the mix. Here is my psuedo code for it:

function controller {
    $scope.$watch(myService.value, function(newVal) {
        $scope.value = newVal;
    });

}

Any pointers on how to avoid using the services scope to update the controller would be appreciated.

Thanks a lot

appthat
  • 796
  • 2
  • 8
  • 30
  • May be `function controller($scope, mySvc){}`? – vp_arth Dec 23 '14 at 19:38
  • 1
    That's not even valid code for an angular controller. Question isn't clear and it doesn't help when code is invalid and doesn't show much. WHat does `dragging service scope into it` even mean? – charlietfl Dec 23 '14 at 19:43
  • like i said its pseudo code, rough idea of what I have. right now the $watch is bringing in the entire scope of the service. How could I work it so I am not reading from the services scope in the controller? – appthat Dec 23 '14 at 20:05
  • Have look on this post: http://stackoverflow.com/questions/12576798/how-to-watch-service-variables – arman1991 Dec 24 '14 at 01:18

1 Answers1

0

You could use a pretty cool feature of Angular. Angularjs comes with a built in messaging system for communicating between modules/sevices/factories etc.

In your service you could use

$rootScope.$broadcast('value:changed', { value: newValue });

and in your controller you can catch the change like so:

$scope.$on('value:changed', function(message) {
   $scope.value = message.newValue;

});

Of course, to use this approach you need a way to know when that value will change so you can broadcast it to the controller.

Hoped this helped! Let me know!

Cheers

For more info on $broadcast (and/or $emit) here's a ref: Why do we use $rootScope.$broadcast in AngularJS? Official documentation: https://docs.angularjs.org/api/ng/type/$rootScope.Scope

Community
  • 1
  • 1
Andrei CACIO
  • 2,001
  • 12
  • 24