$ watch内部指令仅触发一次 [英] $watch is firing only once inside directive

查看:582
本文介绍了$ watch内部指令仅触发一次的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我是angular js的新手,所以请有人帮我.我在这里有我的模板:

I am new to angular js, so Please some one help me out.I have my template here:

<form ng-model="signup" form-valid>
    <input type="text" name="username" ng-model="signup.username">{{signup}}
</form>

我的指令是这样的:

app.directive("formValid",function(){

 return {
    restrict:"A",
    require:"ngModel",
    link:function(scope,element,attrs){
          scope.$watch(attrs.ngModel,function(newValue){
              if(newValue){
                 console.log(newValue);
              }
          });
       }
   }});

每当我在文本框中输入一些值时,模型就会更改,因此应该触发"$ watch".但是在这里,当我第一次在文本框中输入任何值时,"$ watch"仅被触发一次.谢谢.

When ever I am entering some value into text box the model is changing and accordingly "$watch" should fired.But in here "$watch" is fired only once when for the first time I enter any value in to text box.Thanks in advance.

推荐答案

使用ngModelController时,监视模型上的更改的标准方法是创建formatter:

When you use ngModelController, the standard way for watching changes on the model is by creating a formatter:

link: function(scope, element, attrs, ngModelCtrl) {
    ngModelCtrl.$formatters.push(function(value) {
        // Do something with value
        return value;
    });
}

请记住,格式化程序仅在直接更改模型时触发.如果更改来自用户界面(即用户更改了某些内容),则会触发解析器.因此,您可能还需要这样做:

Keep in mind that formatters are only triggered when the model is changed directly. If the change comes from the UI (i.e. the user changes something), then parsers are triggered instead. So you may need to do this as well:

ngModelCtrl.$parsers.push(function(value) {
    // Do something with value
    return value;
});

工作柱塞

我建议您阅读 ngModelController 文档,以便您完全理解这些管道如何运作.

I suggest that you read ngModelController documentation so you understand exactly how those pipelines work.

但是,如果您希望做的所有事情都在模型更改时得到通知(您既不需要也不不需要格式化或解析任何内容),那么您可以做些更简单的事情:

But if all you want to do is get notified when the model changes (you don't want or need to neither format nor parse anything), then you can do something simpler:

scope: { model: '=ngModel' },
link: function(scope) {
    scope.$watch('model', function(value) {
        // Do something with value
    });
}

工作柱塞

但是考虑到指令的名称formValid,我认为使用ngModelController是正确的方法.

But given your directive's name, formValid, I think that using ngModelController is the correct approach.

更新

值得一提的是ngModelController可以说有一个缺点:它不适用于引用"类型(例如数组,对象).有关更多详细信息,请参见此处.

It's worth mentioning that ngModelController has arguably one shortcoming: it doesn't work very well with "reference" types (e.g. arrays, objects). More details on that can be found here.

这篇关于$ watch内部指令仅触发一次的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆