按下键时清除输入字段

时间:2016-06-22 08:27:47

标签: angularjs angularjs-directive

我尝试清除angularjs指令中 keypress 事件的输入字段。

HTML:

<input class="magic-input" type="number" ng-model="demo.input">

指令:

.directive('magicInput', function () {
return {
    restrict: 'C',
    require: 'ngModel',
    link: function (scope, elem, attrs, ngModel) {
        elem.bind('keypress', function () {
            ngModel.$setViewValue('');
            ngModel.$render(); 
        });
    }
}
});

这里的问题是指令清除当前文本但按下的键仍保留在输入字段中。

here是解决这个问题的小提琴。

2 个答案:

答案 0 :(得分:3)

我可以理解你的问题。我可以建议在“ keypress ”事件的地方尝试使用“ keyup ”事件。

试试这个

<section name="microsoft.visualstudio.testtools" type="Microsoft.VisualStudio.TestTools.UnitTesting.TestConfigurationSection,
           Microsoft.VisualStudio.QualityTools.UnitTestFramework,
           Version=10.0.0.0, Culture=neutral,
           PublicKeyToken=b03f5f7f11d50a3a"/>

检查这个小提琴Here

答案 1 :(得分:1)

将您的链接功能改为以下内容:

e.preventDefault()

mymodel.beforeRemote('method',function(context,unused,next()) { //where can i forward my new value, and what is a 'unused' ??? next() });会阻止按键事件完成。