Consider this scenario:
<div class="form-group" ng-class="{'has-error': (form.title.$dirty && form.title.$invalid) }">
<label for="title" class="col-sm-2 control-label">Title</label>
<div class="col-sm-10">
<input ng-model="vm.item.name" type="text" class="form-control" name="title" id="title" placeholder="Title" ng-required="true" />
</div>
</div>
I have multiple input fields and the
ng-class="{'has-error': (form.title.$dirty && form.title.$invalid) }"
code seems messy to me.
I want to create a directive that simplifies it to just has-error
, like so:
<form name="form" has-error=".form-group">
...
</form>
// Custom directive definition object.
return {
restrict: "A",
require: "form",
link: function(scope, elements, attributes, form) {
var selector = attributes["hasError"];
// 1. Locate all controls with ng-models
// 2. Validate them
// 3. Find closest element based on provided selector and add the 'has-error' class
}
};
};
.form-group
is the selector for the nearest parent container of an input with ng-model.
The question remains: How can steps 1-3 be implemented in an effective AngularJS manner?