简体   繁体   中英

$watch for value change from inside angular directive when using isolate scope

I am trying to find a way to watch for a changing value of a property in an object I am scoping my directive to and I'm unable to figure out what I'm doing wrong here.

Here is my directive code:

.directive('selectService', [function() {
  return {
    restrict: 'EA',
    scope: {
      distribution: '='
    },
    link: function(scope, element, attrs) {
      scope.$watch(scope.distribution.name, function(newValue) {
        console.log("Changed to " + newValue);
      });

So say distribution at the time this gets run is something like this:

{ name: '', type: 'all' ... }

I want to $watch for when the property 'name' changes to have a value so that I can enable a select menu in my directive. Everything I've done seems to not work. Any help is appreciated.

Just use watch the normal way, provide a string representing property on the scope or a function that returns the value to be watched.

  scope.$watch('distribution.name', function(newValue) {
    console.log("Changed to " + newValue);
  });

for setting up deep watch on the object distribution set the third argument of watch to true. When you provide scope.distribution.name as the first argument to the watch function, it will just set up watch on the value (at that time) of scope.distribution.name which is incorrect.

Demo

 angular.module('app', []).controller('ctrl', function($scope) { $scope.distribution = {}; }).directive('selectService', [ function() { return { restrict: 'EA', scope: { distribution: '=' }, link: function(scope, element, attrs) { scope.$watch("distribution.name", function(newValue) { console.log("Changed to " + newValue); }); } } } ]) 
 <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script> <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script> <div ng-app="app" ng-controller="ctrl"> <input ng-model="distribution.name">{{distribution.name}} <div select-service distribution="distribution"></div> </div> 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM