【发布时间】:2018-05-04 17:13:39
【问题描述】:
在下面的示例中,当用户关闭弹出窗口时出现错误,我试图将控制器值设置为 null。但是,尽管我正在更新 $viewValue 和 $modelValue,但 angularjs 不知何故采用了旧值。如果您输入input 任何值,例如1,然后按Tab,1 秒后您将看到1.00,但是我试图将其设置为null(并查看值应该是空字符串)。
(function () {
var module = angular.module('TestApp', []);
module.directive('decimalTextbox', ['$timeout', function ($timeout) {
return {
restrict: 'A',
replace: false,
require: '?ngModel',
scope: {
onValidate: '='
},
link: function (scope, element, attrs, ctrl) {
ctrl.$formatters.unshift(function (value) {
return value != null ? parseFloat(value).toFixed(2) : '';
});
ctrl.$parsers.unshift(function (value) {
return value == '' ? null : parseFloat(value);
});
$(element).on('blur', function () {
$timeout(function () {
var result = { isValid: true, value: ctrl.$modelValue };
scope.onValidate(result);
if (!result.isValid) {
// show popup with close button here
// to simplify example I use setTimeout
setTimeout(function () {
$(element).val('');
ctrl.$viewValue = '';
ctrl.$modelValue = null;
scope.$apply();
console.log(ctrl.$modelValue);
}, 1000);
}
});
});
}
};
}]);
module.controller('TestController', ['$scope', function (scope) {
scope.someValue = 3;
scope.validate = function (result) {
result.isValid = false;
};
}]);
})();
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.6.6/angular.min.js"></script>
<div ng-app="TestApp" ng-controller="TestController">
<input
type="text"
ng-model="someValue"
decimal-textbox=""
on-validate="validate">
<h3>{{ someValue }}</h3>
</div>
【问题讨论】:
-
不要直接设置,而是使用$setViewValue方法。
标签: angularjs angularjs-directive angularjs-ng-model