Reputation: 839
I am new to angularjs, I appreciate all the help I can get.
I have an angular form where user can create key value input fields. I am applying logic to check if that pair user have entered or not. If they have entered that then show message for that specific input fields only. However, directive shows message to every input field.
function ruleValue(val){
var code = scope.listOfValue[scope.index].code;
var value = scope.listOfValue[scope.index].value;
var idx = parseInt(scope.index);
var list = scope.listOfValue;
//compare code with code
// if code is same then check it's value
// if both same then throw an error
for (var i=0; i<list.length; i++) {
if (i !== idx) {
if (list[i].code === list[idx].code && list[i].value === val) {
console.log(list[i].value, i )
console.log(list[idx].value, idx)
console.log(i, idx, list[i], list[idx]);
ctrl.$setValidity('userRuleAlreadyExist', false);
break;
}
}else{
ctrl.$setValidity('userRuleAlreadyExist', true);
}
}
};
ctrl.$parsers.unshift(function(value){
ruleValue(value);
return value
});
HTML:
<div ng-show="userRule.type === 'maplist'">
<label>Values</label>
<div class="row" ng-repeat="v in userRule.values" ng-show="userRule.type === 'maplist'" >
<div class="col-sm-5">
<div class="form-group">
<label class="sub-list">Code:*</label>
<input name="code"
type="text"
ng-model="v.code"
class="form-control"
placeholder="M"
no-special-char
user-rule-values-check
index="{{$index}}"
cv="code"
list-of-value="userRule.values"
required>
<div class="help-block" ng-messages="form.code.$error"
ng-if="form.code.$touched && form.code.$error">
<div ng-messages-include="partials/includes/messages.html"></div>
</div>
</div>
</div>
<div class="col-sm-5">
<div class="form-group">
<label class="sub-list">Value:*</label>
<input name="value"
type="text"
ng-model="v.value"
class="form-control"
placeholder="Medical"
no-special-char
user-rule-values-check
index="{{$index}}"
cv="value"
list-of-value="userRule.values"
required>
<div class="help-block" ng-messages="form.value.$error"
ng-if="form.value.$touched && form.value.$error">
<div ng-messages-include="partials/includes/messages.html"></div>
</div>
</div>
Upvotes: 0
Views: 44
Reputation: 2948
You are using an ng-repeat
within the form, so there are multiple form.value
so when one of them has an error, the message will show for all of them. You really want nested <ngForm>
elements.
<div class="row" ng-repeat="v in userRule.values" ng-show="userRule.type === 'maplist'" >
<ng-form name="rowForm">
...
<input name="value"/>
<div ng-messages="rowForm.value.$error" ng-if=rowForm.value.$touched && rowForm.value.$error">
...
</div>
</ng-form>
</div>
Reference: https://docs.angularjs.org/api/ng/directive/form
Upvotes: 1