gpt4 book ai didi

AngularJS:隐藏 ng-message 直到点击表单提交按钮

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

这是在 AngularJS (1.x) 中使用 ng-messages 的典型示例:

<form name="demoForm">
<input name="amount" type="number" ng-model="amount" max="100" required>

<div ng-messages="demoForm.amount.$error">
<div ng-message="required">This field is required</div>
</div>

<button type="submit">test submit</button>
</form>

见: http://jsfiddle.net/11en8swy/3/

我现在想更改此示例,以便“此字段是必需的”错误仅在触摸该字段( $touched )或用户点击提交按钮时显示。

我无法使用 ng-submitted表单上的类,因为验证错误阻止了表单的提交。

我该怎么做?

谢谢

最佳答案

您可以使用 ng-show 执行此操作:

<div ng-messages="demoForm.amount.$error" ng-show="demoForm.amount.$touched">
<div ng-message="required">This field is required</div>
</div>

并使用自定义指令。查看工作演示:

var app = angular.module('app', ['ngMessages']);

app.controller('mainCtrl', function($scope) {

});
app.directive('hasFocus', function($timeout) {
return {
restrict: 'A',
require: 'ngModel',
link: function(scope, element, attr, ctrl) {
element.on('focus', function() {
$timeout(function() {
ctrl.hasFocusFoo = true;
})
});

element.on('blur', function() {
$timeout(function() {
ctrl.hasFocusFoo = false;
})
});
}
}
})
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.5.8/angular.min.js"></script>
<script src="//ajax.googleapis.com/ajax/libs/angularjs/1.5.8/angular-messages.js"></script>

<body ng-app="app" ng-controller="mainCtrl">
<form name="demoForm">
<input name="amount" type="number" ng-model="amount" max="100" required has-focus>

<div ng-messages="demoForm.amount.$error" ng-show="demoForm.amount.$touched || demoForm.amount.hasFocusFoo">
<div ng-message="required">This field is required</div>
</div>

<button type="submit">test submit</button>
</form>
</body>


该指令基本上是设置另一个 hasFocusFoo ngModel Controller 上的字段,然后我们可以轻松使用该指令。

关于AngularJS:隐藏 ng-message 直到点击表单提交按钮,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39524445/

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