Issue
I have the following code
<div>
<button ng-click="myController.addEmptyStudent()">+</button>
</div>
<div ng-repeat="student in myController.students">
<input type="text" ng-model='student['Name']" required>
<input type="text" ng-model='student['Address']" required>
</div>
Now, Since it is creating input boxes when I click on (+) plus button.
I want to validate that no two Names are same before submitting the
form.
Solution
Finally I got the solution.
Changes in controller
function studentNameChanged() {
vm.duplicateNames = false;
let studentNamesArray = students.map(item => item['studentName']);
vm.duplicateNames = studentNamesArray.some( (item, index) => {
return (studentNamesArray.indexOf(item) !== index)
});
}
Changes in HTML file
<div>
<button ng-click="myController.addEmptyStudent()">+</button>
</div>
<div ng-repeat="student in myController.students">
<input type="text" ng-change="myController.studentNameChanged()" ng-model="student['Name']" required>
<input type="text" ng-model="student['Address']" required>
</div>
<div>
<div style="color:red;" ng-show="myController.duplicateNames">
Attribute Names must be different
</div>
</div>
Answered By - Satish Dalal
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.