我试图强制输入带有所需属性的数字,使其始终具有一些值,而在空的情况下,使输入号为零。
<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根本不起作用。
我希望这个指令尽可能通用,所以我不想在范围中指定模型名称。
发布于 2015-06-26 00:58:31
这是另一种方法。
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)
})
}
}
};
});http://plnkr.co/edit/4yDTNUfdpu2ql1EmTZ3B?p=preview
发布于 2015-06-26 00:48:59
我个人会使用isNaN(parseInt('')),因为我认为它比确切的等价物更明确。这两种方法都是可以肯定的,但目前还不清楚您是否正在检查是否缺少条目。
这个解决方案在我看来也很混乱,但它是朝着正确方向迈出的一步。也许有更多经验的人能看出来。
App.directive('input', function () {
return {
scope: {},
link: function ($scope, $element, $attrs, ngModel) {
if ($attrs.type == 'number') {
if ($element[0].required) {
$element.on('blur', function(){
if(isNaN(parseInt(ngModel.$viewValue))){
scope.$apply(function(){
ngModel.$viewValue = 0;
}
}
});
}
}
}
};
}); 发布于 2015-06-26 01:03:30
AngualarJS:
var replaceWithZeros = (function(angular) {
"use strict";
var demo = angular.module('demo', []);
demo.controller('demoCtrl', function($scope) {
$scope.someModel = '0.00';
$scope.someFunction = function(curVal) {
if (!curVal) {
$scope.someModel = '0.00';
}
};
});
})(window.angular);HTML:
<main ng-app="demo" ng-controller="demoCtrl">
<input ng-model="someModel" ng-blur="someFunction(someModel)" required="required"/>
</main>这里的演示显示了所有的工作在一起,标记是在HTML上面,但它是在玉在演示希望,不造成任何混乱。
http://codepen.io/nicholasabrams/pen/xGPvJd
https://stackoverflow.com/questions/31062910
复制相似问题