简体   繁体   English

观看ngModel值从父元素上的指令更改

[英]Watch ngModel value change from directive on parent element

I have a directive which watches for change in an input field 我有一条指令,监视输入字段中的更改

directive('autocomplete', function(){
    return {
        link: function(scope, element, attrs){
            scope.$watch(attrs.ngModel, function(){
                console.log('change');
            });
        }
    };
});

This works fine on the following element 在以下元素上工作正常

<input type='text' ng-model='searchTerm' autocomplete>

But what if I was to put my directive on an ancestor element, like this: 但是,如果我要将指令放在祖先元素上,例如:

<div autocomplete>
    <input type='text' ng-model='searchTerm'>
</div>

How could I still watch the input for change then? 那我怎么还能看着输入的变化呢?

Simply put: you could, but you shouldn't . 简而言之: 您可以,但不应该

First, the ngModel directive has a controller . 首先, ngModel指令具有一个controller Its $viewChangeListeners property is probably what you'd really want to use (as your "autocomplete" directive is probably going to be looking out just for view value changes). 它的$viewChangeListeners属性可能是您真正想要使用的属性(因为您的“自动完成”指令可能会仅查找视图值更改)。 You can just push your change listener into that array. 您可以将更改侦听器推入该数组。

Second (and more to the point), you shouldn't direct that kind of functionality from the ancestor element only. 其次(更重要的是),您不应该仅从祖先元素中引导这种功能。 If you wish to interact with ngModel , you'd better put your directive right on the element using it or its descendant (not an option with an <input> ). 如果您希望与ngModel进行交互, ngModel最好将指令直接使用它或其后代(而不是带有<input>的选项)放在元素上。 This doesn't stop you from putting some common logic on an ancestor and interacting with that ancestor (much like ngModel interacts with ngForm ). 这并不会阻止您在祖先上放置一些通用逻辑并与祖先进行交互(就像ngModelngForm交互)。


If you don't care about should s and shouldn't s, you can always either 如果您不关心应该不应该 ,则始终可以

  1. put a name on your input and get the ngModelController from the ngForm (if your directive is under it), or 在输入中输入一个namengModelControllerngForm获取ngForm (如果您的指令位于其下),或者
  2. find the <input> and get the ngModelController using angular.element(...).controller('ngModel') . 找到<input>并获得ngModelController使用angular.element(...).controller('ngModel')

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

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