有一个对象包含错误消息列表:错误代码+错误文本。我想在页面上显示一些错误消息(错误代码数组)(在某些地方),而不需要任何额外的验证。
我已经尝试用AngularJS做here in jsFiddle,但似乎我可能错误的方法是如何做得更好,因为我是AngularJS的新手。这就是为什么我要求SO社区思考和帮助,如果这看起来很有趣。
以下是代码,或从jsFiddle查看。
除了 angular.js 之外,还添加了 angular-messages.js :
HTML:
<h3>So what I need here is actually to display errors that are returned by my custom showErrorsWeWant service. The array of errors can be different. No additional validation is needed. As result, I'm not sure if to stick with ng-message(s) or ng-if(s) (so both ng-message and ng-if are used in this example)</h3>
<h4>
As result, once the page is loaded, only 'You did not enter your name' and "'text for error04'" should be displyaed, based on
return ['error01', 'error04'];
</h4>
<h5>For three errors in returned array - then 3 respective errors displayed for these two inputs.
The very <u>IMPORTANT</u> thing: I don't know how to stick so each error know its place - is it for first input or for the second one. Still thinking how to make it done. Probably the additional property should be assigned in the json object.</h5>
<form name="myForm">
<label>Name:</label>
<input type="text" name="myName" ng-model="name" ng-minlength="5" ng-maxlength="5" required placeholder="type here" />
<div ng-messages="myForm.myName.$error" style="color:red; padding-left: 60px;">
<div ng-message="required">{{ errors['error01'] }}</div>
<div ng-message="minlength">{{ errors['error02'] }}</div>
<div ng-message="maxlength">{{ errors['error03'] }}</div>
</div>
</form>
<div id="statusBlock">
<label>City:</label>
<input type="text" placeholder="and type here">
<div style="color:red; padding-left: 60px;">
<div ng-if="errorsArr[1]=='error04'">{{ errors['error04'] }}</div>
<div ng-if="1<3">{{ errors['error05'] }}</div>
<div ng-message="maxlength">{{ errors['error06'] }}</div>
</div>
</div>
</div>
</body>
JS代码:
var myApp = angular.module('myApp', ['ngMessages']);
myApp.controller('myController', ['$scope', 'showErrorsWeWant', function ($scope, showErrorsWeWant){
$scope.name = "";
$scope.errors= {
error01: 'You did not enter your name',
error02: 'Your name is less than 5 symbols',
error03: 'Yr name is 6+ symbols',
error04: 'text for error04',
error05: 'text for error05',
error06: 'text for error06'
}
$scope.errorsArr = showErrorsWeWant;
console.log($scope.errorsArr);
}]);
myApp.service('showErrorsWeWant', [function (){
return ['error01', 'error04'];
}]);
如果我错过了什么,请告诉我。谢谢。
答案 0 :(得分:1)
您可以使用ng-repeat
为每个元素创建一个ng-message
的元素:
<div ng-messages="myForm.myName.$error" style="color:red; padding-left: 60px;">
<div ng-message="{{key}}" ng-repeat="(key, errorMessage) in errors">{{ errorMessage }}</div>
</div>
为此,errors
对象的键必须与错误类型匹配:
$scope.errors= {
required: 'You did not enter your name',
minlength: 'Your name is less than 5 symbols',
maxlength: 'Yr name is 6+ symbols'
};