使用AngularJS绑定处理IE的清除按钮

dpr*_*ero 19 internet-explorer angularjs

IE在每个文本输入中都有一个"X",用于清除输入.但是,单击此按钮时,它会清除文本框,但不会更新输入绑定的Angular模型.

<input type="text" ng-model="name" />
Run Code Online (Sandbox Code Playgroud)

有关该行为的示例,请参见http://jsfiddle.net/p5x1zwr9/.

有关该行为的视频,请参见http://youtu.be/LFaEwliTzpQ.

我正在使用IE 11.

编辑:似乎有一个Knockout的解决方案,但我不知道如何将它应用于AngularJS:使用Knockout绑定处理IE 9和10的清除按钮

更新:Jonathan Sampson帮助我意识到这实际上在1.3.6之前的AngularJS版本中有效,所以这可能是一个新的Angular bug.

更新:已解决的问题:https://github.com/angular/angular.js/issues/11193

Mic*_*ach 18

输入表单中的X按钮对于IE10 +是原生的,你不能对它做任何事情,但只能用CSS隐藏它:

input[type=text]::-ms-clear {
   display: none;
}
Run Code Online (Sandbox Code Playgroud)

然后,您可以创建自己的指令来模仿这种行为.只需创建一个跨度,将其放在输入内部并添加ng-click,这将清除输入的模型值.


小智 7

我为输入文本元素创建了这个Angular指令,当单击clear('X')按钮时,它手动调用元素的change()事件.这解决了我们项目的问题.我希望它能帮助别人.

angular.module('app')
    .directive('input', function () {
        return {
            restrict: 'E',
            scope: {},
            link: function (scope, elem, attrs) {

                // Only care about textboxes, not radio, checkbox, etc.
                var validTypes = /^(search|email|url|tel|number|text)$/i;
                if (!validTypes.test(attrs.type)) return;

                // Bind to the mouseup event of the input textbox.  
                elem.bind('mouseup', function () {

                    // Get the old value (before click) and return if it's already empty
                    // as there's nothing to do.
                    var $input = $(this), oldValue = $input.val();
                    if (oldValue === '') return;

                    // Check new value after click, and if it's now empty it means the
                    // clear button was clicked. Manually trigger element's change() event.
                    setTimeout(function () {
                        var newValue = $input.val();
                        if (newValue === '') {
                            angular.element($input).change();
                        }
                    }, 1);
                });
            }
        }
    });
Run Code Online (Sandbox Code Playgroud)

感谢这个答案(在IE10上用清除图标清除文本输入时触发事件),JavaScript代码检测到清除按钮单击.