gpt4 book ai didi

AngularJS 仅在模糊时更新模型

转载 作者:行者123 更新时间:2023-12-02 01:56:53 25 4
gpt4 key购买 nike

我有一个要求,即只有在输入模糊或按下回车时才更新模型,并且错误/成功消息只会在此之后显示,而不是在输入期间显示。以前我使用的是 AngularJS 1.2 rc2 并具有以下代码:

Javascript:

angular.module('app', []).directive('ngModelOnblur', function () {
return {
restrict: 'A',
require: 'ngModel',
link: function (scope, element, attrs, ngModelCtrl) {
if (attrs.type === 'radio' || attrs.type === 'checkbox') { return; }
var update = function () {
scope.$apply(function () {
ngModelCtrl.$setViewValue(element.val().trim());
ngModelCtrl.$render();
});
};
element.off('input').off('keydown').off('change').on('focus', function () {
scope.$apply(function () {
ngModelCtrl.$setPristine();
});
}).on('blur', update).on('keydown', function (e) {
if (e.keyCode === 13) {
update();
}
});
}
};
})
.controller('Ctrl', ['$scope', function ($scope) {
$scope.getClass = function (input) {
if (input.$pristine) { return ''; }
return input.$invalid ? 'has-error' : 'has-success';
};
}]);

HTML:

<div ng-controller="Ctrl">
<form name="form" novalidate>
<div ng-class="getClass(form.firstname)">
<input type="text" name="firstname" ng-model="firstname" ng-model-onblur ng-pattern="/^\d{4}$/" />
<div class="error">error</div>
<div class="success">success</div>
$pristine: {{form.firstname.$pristine}}
</div>
</form>
</div>

CSS:

  .error, .success {
display: none;
}
.has-error .error, .has-success .success {
display: block;
}

但是自从我升级到 RC3 后,事情开始出现问题。尽管我删除了输入、更改和按键的事件处理程序,但在输入过程中 $pristine 仍设置为 false,因此将显示消息。

我尝试为指令设置terminal: true, priority: -1,但它仍然不起作用。我做错了什么?

这里是 plunker:http://plnkr.co/edit/8FliNc?p=preview

提前致谢

最佳答案

如果您赋予指令优先级,它对我有用:1. 设置 terminal = true 意味着永远不会调用 ng-model,我认为不支持优先级 -1。

http://plnkr.co/edit/mZyWw8?p=preview

只是我在该指令中发现的一些小问题:当您重新聚焦输入时,模型将被重置(表单设置为原始状态),如果模型有效,则会重置。如果您清空输入,则在设置模型后,模型不会设置为未定义。

关于AngularJS 仅在模糊时更新模型,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19488884/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com