There is an object that contains a list of error messages: error code + error text. There is an array of error messages (array of error codes) I would like to display on the page (in some places) without any additional validation.
I've tried to do that here in jsFiddle with AngularJS, but seems like I could be on the wrong way of how to do it better as I'm new to AngularJS. That's why I'm asking SO community to think and to help, if that's look an interesting problem.
Here is a code below or check from jsFiddle.
Beside angular.js, angular-messages.js was added as well:
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 code:
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'];
}]);
Please let me know if I've missed something. Thank you.