简体   繁体   English

使用隔离范围时,$ watch从内部角度指令中更改值

[英]$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. 我想监视$ name属性何时具有值,以便可以在指令中启用选择菜单。 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. 只需以通常的方式使用watch即可,在范围上提供一个表示属性的字符串或一个返回要监视值的函数。

  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. 要在对象distribution上设置深入监视,请将watch的第三个参数设置为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. 当将scope.distribution.name提供给watch函数的第一个参数时,它将只是在不正确的scope.distribution.name值(当时)上设置watch。

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> 

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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