angularjs - $watch does not work when changing scope variables inside a service -


i using service change of scope a's variables. when try $watch changes on variables nothing happens.

the basic setup shown below. use $watch in own custom directive add element. if impossible @ least able use $watch inside controller.

i made plunkr here. can see $scope.somevar changes $watch never fired on either controller or directive.

enter image description here

app.factory("changerservice", function() {   var $scope;   function change(to) {     $scope.somevar = to;   }   function setscope(scope) {     $scope = scope;   }   return {     change: change,     setscope: setscope   } });  app.controller("bar", ["$scope", "changerservice", function ($scope, changerservice) {     $scope.somevar = true;     changerservice.setscope($scope);     $scope.showimg = function (val) {         changerservice.change(val);         $scope.state = $scope.somevar;     };      $scope.$watch($scope.somevar, function (newval, oldval) {         $scope.watchcontroller = newval ? newval : "undefined";     }); }]);  app.directive("mydirective", function () {     return {         link: function (scope, element, attrs) {             scope.$watch(scope.somevar, function (newval, oldval) {                 scope.watchdirective = newval ? newval : "undefined";             });         }     } }); 

after examining code noticed watch expression object must string.

example:

app.controller("bar", ["$scope", "changerservice", function ($scope, changerservice) {     $scope.somevar = true;     changerservice.setscope($scope);     $scope.showimg = function (val) {         changerservice.change(val);         $scope.state = $scope.somevar;     };      $scope.$watch("somevar", function (newval, oldval) {         $scope.watchcontroller = newval ? newval : "undefined";     }); }]);  app.directive("mydirective", function () {     return {         link: function (scope, element, attrs) {             scope.$watch("somevar", function (newval, oldval) {                 scope.watchdirective = newval ? newval : "undefined";             });         }     } }); 

Comments

Popular posts from this blog

android - Get AccessToken using signpost OAuth without opening a browser (Two legged Oauth) -

org.mockito.exceptions.misusing.InvalidUseOfMatchersException: mockito -

google shop client API returns 400 bad request error while adding an item -