by changing a service from 'outside' angular js the watchers stop working

StackOverflow https://stackoverflow.com/questions/23571184

  •  19-07-2023
  •  | 
  •  

سؤال

I am doing so:

    angular.element('body').injector().get("myService").somevar = true

And somewhere else I'm grabbing it:

    $scope.$watch( function () { return myService.somevar; }, function (somevar) {
        console.log(somevar)
    });

But the watcher does not trigger, even though if i check the value through the console it has in fact changed

هل كانت مفيدة؟

المحلول

As already mentioned, you need to use $apply:

$apply() is used to execute an expression in angular from outside of the angular framework. (For example from browser DOM events, setTimeout, XHR or third party libraries). Because we are calling into the angular framework we need to perform proper scope life cycle of exception handling, executing watches.

For example:

var element = angular.element(document.querySelector('body'));
var service = element.injector().get('myService');
var scope = element.scope();

scope.$apply(function () {
  service.somevar = true;
});

Demo: http://plnkr.co/edit/Iy3CiRzDdxFTwVq68JWi?p=preview

مرخصة بموجب: CC-BY-SA مع الإسناد
لا تنتمي إلى StackOverflow
scroll top