请注意,即使通过验证的值也不会通过解析器使其完好无损。解析器返回正确的值,但是当调用格式化程序时,旧值仍然存在于模型中。谁可以给我解释一下这个?
这是plnkr
http://plnkr.co/edit/uSLkKtLZIU63wRou3x8V?p=preview
和代码
angular.module('timeEntryModule', []).directive('timeEntryTotalHoursInput', function() {
return {
require: '^ngModel',
link: function($scope, $element, $attrs, ngModel) {
ngModel.$formatters.push(function (modelValue) {
if (modelValue === 0) {
return undefined;
} else {
return modelValue.toFixed(2);
}
});
ngModel.$parsers.push(function (viewValue) {
var tempVal = parseFloat(viewValue);
if (tempVal) {
ngModel.$setValidity('timeEntryInputError', true);
ngModel.$modelValue = tempVal;
} else {
ngModel.$setValidity('timeEntryInputError', false);
ngModel.$modelValue = undefined;
}
return ngModel.$modelValue;
});
}
};
});
angular.module('timeEntryModule').controller('TimeEntryCtrl', ['$scope', function ($scope) {
$scope.testproperty = 2;
}]);
<!doctype html>
<html ng-app="timeEntryModule">
<head>
<script src="http://ajax.googleapis.com/ajax/libs/angularjs/1.0.5/angular.min.js"></script>
<script src="script.js"></script>
</head>
<body ng-controller="TimeEntryCtrl">
<input ng-model="testproperty" time-entry-total-hours-input />
</body>
</html>
提前致谢!