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.
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
Post a Comment