Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
483 views
in Technique[技术] by (71.8m points)

events - How to create on-change directive for AngularJS?

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.

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

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.

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?

EDIT

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.

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

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

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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;
                    });
                }
            });
        }
    };        
});

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...