如何创建变更指令为AngularJS? [英] How to create on-change directive for AngularJS?

查看:147
本文介绍了如何创建变更指令为AngularJS?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

通常情况下势必每次用户模型NG-模型更新推动的关键是:

Normally ng-model updates bound model each time user pushes the key:

<input type="text" ng-model="entity.value" />

这在几乎所有情况下的伟大工程。

This works great in almost every case.

但我需要的时候onchange事件,而不是它发生更新时的onkeyup / onKeyDown事件。

But I need it to update when onchange event occurs instead when onkeyup/onkeydown event.

在老版本的角度有哪些工作一样NG-模型现在工作的NG-模型即时指令(至少在用户 - 我不知道他们的事情的实现)。
所以,如果我只是给了NG-型号较旧版本的它被更新模型的onchange当我指定的NG-模型即时它更新模型onkeypup。

In older versions of angular there was a ng-model-instant directive which worked same as ng-model works now (at least for the user - i don't know anything about their implementations). So in older version if I just gave ng-model it was updating the model onchange and when I specified ng-model-instant it was updating the model onkeypup.

现在我需要NG-模型的元素的变事件中使用。我不希望它是瞬间。什么是这样做的最简单的方法?

Now I need ng-model to use on "change" event of the element. I don't want it to be instant. What's the simplest way of doing this?

修改

输入仍然反映其他任何更改模型 - 如果模型将在其他地方进行更新,输入的值应反映这种变化。

The input still has to reflect any other changes to the model - if the model will be updated in other place, value of the input should reflect this change.

我需要的是有NG-模式指令工作,就像它在旧版本angularjs的工作。

What I need is to have ng-model directive to work just like it worked in the older versions of angularjs.

下面是什么,我试图做一个解释:
http://jsfiddle.net/selbh/EPNRd/

Here is an explanation of what I'm trying to do: http://jsfiddle.net/selbh/EPNRd/

推荐答案

下面我创建的onChange指示你。 演示 http://jsfiddle.net/sunnycpp/TZnj2/52/

Here I created onChange directive for you. Demo: http://jsfiddle.net/sunnycpp/TZnj2/52/

app.directive('onChange', function() {    
    return {
        restrict: 'A',
        scope:{'onChange':'=' },
        link: function(scope, elm, attrs) {
            scope.$watch('onChange', function(nVal) { elm.val(nVal); });            
            elm.bind('blur', function() {
                var currentValue = elm.val();
                if( scope.onChange !== currentValue ) {
                    scope.$apply(function() {
                        scope.onChange = currentValue;
                    });
                }
            });
        }
    };        
});

这篇关于如何创建变更指令为AngularJS?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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