Angularjs: input[text] ngChange 在值改变时触发 [英] Angularjs: input[text] ngChange fires while the value is changing

查看:27
本文介绍了Angularjs: input[text] ngChange 在值改变时触发的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

ngChange 在值改变时触发(ngChange 与经典的 onChange 事件不同).我如何将经典的 onChange 事件与 angularjs 绑定,只有在提交内容时才会触发?

ngChange is firing while the value is changing (ngChange are not similiar to the classic onChange event). How can i bind the classic onChange event with angularjs, that will only fire when the contents are commited?

当前绑定:

<input type="text" ng-model="name" ng-change="update()" />

推荐答案

这篇文章 显示了一个指令示例,该指令将模型更改延迟到输入,直到 blur 事件触发.

This post shows an example of a directive that delays the model changes to an input until the blur event fires.

这里是一个小提琴,展示了使用新的 ng-model-on-blur 指令的 ng-change.请注意,这是对原始小提琴的轻微调整.

Here is a fiddle that shows the ng-change working with the new ng-model-on-blur directive. Note this is a slight tweak to the original fiddle.

如果你将指令添加到你的代码中,你会改变你的绑定:

If you add the directive to your code you would change your binding to this:

<input type="text" ng-model="name" ng-model-onblur ng-change="update()" />

这是指令:

// override the default input to update on blur
angular.module('app', []).directive('ngModelOnblur', function() {
    return {
        restrict: 'A',
        require: 'ngModel',
        priority: 1, // needed for angular 1.2.x
        link: function(scope, elm, attr, ngModelCtrl) {
            if (attr.type === 'radio' || attr.type === 'checkbox') return;

            elm.unbind('input').unbind('keydown').unbind('change');
            elm.bind('blur', function() {
                scope.$apply(function() {
                    ngModelCtrl.$setViewValue(elm.val());
                });         
            });
        }
    };
});

<小时>

注意:正如@wjin 在下面的评论中提到的,Angular 1.3(目前处于测试阶段)通过 ngModelOptions 直接支持此功能.有关详细信息,请参阅文档.


Note: as @wjin mentions in the comments below this feature is supported directly in Angular 1.3 (currently in beta) via ngModelOptions. See the docs for more info.

这篇关于Angularjs: input[text] ngChange 在值改变时触发的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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