在这种小问题中,目标是根据控制器中的验证(而不是内置required或min- length)显示错误消息。设置ng-message-exp时,不显示消息错误。关于如何使这项工作更好或如何ng- message实际工作的任何想法都与错误或模型有关?
required
min- length
ng- message
的HTML
<body ng-app="ngMessagesExample" ng-controller="ctl"> <form name="myForm" novalidate ng-submit="submitForm(myForm)"> <label> This field is only valid when 'aaa' is entered <input type="text" ng-model="data.field1" name="field1" /> </label> <div ng-messages="myForm.field1.$error" style="color:red"> <div ng-message-exp="validationError">this is the error</div> </div> <br/><br/> <button style="float:left" type="submit">Submit</button> </form>
Java脚本
var app = angular.module('ngMessagesExample', ['ngMessages']); app.controller('ctl', function ($scope) { $scope.submitForm = function(form) { if (form.field1.$modelValue != 'aaa') { $scope.validationError = true; console.log('show error'); } else { $scope.validationError = false; console.log('don\'t show error'); } }; });
您的主要ng- messages论点受到束缚myForm.field1.$error,但您从未真正向清单添加错误form.field1.$error。因此,在您的控制器中,只需$error通过$setValidity(field, isValid)以下命令向对象手动添加错误:
ng- messages
myForm.field1.$error
form.field1.$error
$error
$setValidity(field, isValid)
if ($scope.data.field1 != 'aaa') { form.field1.$setValidity('validationError', false); // Angular will make form.field1.$error.validationError = true; } else { form.field1.$setValidity('validationError', true); // Angular will make form.field1.$error.validationError = false; }
然后,您可以让ng-message指令执行其工作。提供的子元素已经ng-message被评估为其父级的属性ng- messages(请注意s)。因此,通常将其与父元素一起用作form元素的$error对象,而将内部子元素用作$error.required或的属性$error.validationError。不需要ng- message-exp这里:
ng-message
s
$error.required
$error.validationError
ng- message-exp
<div ng-messages="myForm.field1.$error" style="color:red"> <div ng-message="validationError">this is the error</div> </div>
固定塞