当我用数字类型的输入eee清除输入字段时,不会清除它。其他所有输入数字将被清除。检查JSFiddle。任何提示将不胜感激。
<div ng-app="app">
<div ng-controller="MainCtrl">
<input type="number" class="form-control" data-ng-model="searchAll">
</input>
<a class="clear" href="" data-ng-click="clearSearch()">X</a>
</div>
</div>
var app = angular.module("app", []);
app.controller("MainCtrl", function ($scope) {
$scope.searchAll = "";
$scope.clearSearch = function () {
$scope.searchAll = "";
};
});
答案 0 :(得分:2)
当ng-model
元素的内容解析为<input type="number">
(不是数字)时,伪指令无法清除该内容。当用户粘贴无效内容或仅键入“ eee”时,就会发生这种情况。
一个解决方法是添加一个自定义指令:
NaN
用法:
app.directive('clearNan', function() {
return {
require: 'ngModel',
link: function(scope, elem, attrs, ngModel) {
ngModel.$formatters.push(function(value) {
if (!value) elem.val(null);
return value;
});
}
};
})
<input type="number" clear-nan ng-model="x" />
angular.module('numfmt-error-module', [])
.directive('clearNan', function() {
return {
require: 'ngModel',
link: function(scope, elem, attrs, ngModel) {
ngModel.$formatters.push(function(value) {
if (!value) elem.val(null);
return value;
});
}
};
})
.run(function($rootScope) {
$rootScope.typeOf = function(value) {
return typeof value;
};
})