我试图强制具有必需属性的输入数字始终具有某个值,而空值则为零。
<input ng-model='someModel' required>
我创建了下一个指令:
App.directive('input', function () {
return {
scope: {},
link: function ($scope, $element, $attrs) {
if ($attrs.type == 'number') {
if ($element[0].required) {
$element.on('blur', function(){
if(this.value===''){
this.value=0;
}
});
}
}
}
};
});
我知道使用 this.value 是错误的,因为它改变了值而不是范围。但我不知道如何更改范围本身。
$scope.value
根本不工作。
我希望该指令尽可能通用,因此我不想在范围内指定模型名称。
最佳答案
这是另一种方法。
App.directive('input', function () {
return {
require: 'ngModel',
link: function (scope, element, attrs) {
if (attrs.type === 'number' && attrs.required) {
function update() {
if (!scope[attrs.ngModel]) {
scope.$apply(function() {
scope[attrs.ngModel] = 0;
});
}
}
element.on('blur', update)
// remove listener when scope is destroyed
scope.$on('$destroy', function() {
element.off('blur', update)
})
}
}
};
});
关于javascript - angular.js 防止空数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31062910/