I have the following Angular/HTML which uses Bootstrap CSS classes to indicate whether a form is valid or not using Angular validation.
<form name="editor" novalidate>
    <div class="form-group" ng-class="{'has-error': editor.name.$dirty && (editor.name.$error.invalid || editor.name.$error.required)}"> 
         <input type="text" class="form-control" name="name" maxlength="150" data-ng-model="name" required />
    </div>
</form>
With more than one div.form-group obviously there is a lot of code repetition. What I would like to do is create an Angular attribute directive which will update the class of the div.form-group element if the input contained within it is invalid.
This is the markup I would like to get to:
<div class="form-group" data-form-group data-input="editor.name">
     ...
</div>
I have the following shell of a directive but I don't know how to monitor the editor.name (or input attribute) in order to update the class.
myApp.directive("formGroup", function () {
return {
    restrict: "A",
    scope: {
        input: "@"
    },
    replace: false,
    link: function (scope, elem, attrs) {
    }
    };
});
I assume I need to put the relevant code in the link function, and perhaps using $watch but other than that I am a bit in the dark
you should use ngModelController properties for doing this:
myApp.directive("formGroupElement", function () {
    return {
       restrict: "A",
       require: "ngModel"
       scope: {
            input: "@"
       },
       replace: false,
       link: function (scope, elem, attrs, ngModelController) {
          //ngModelController.$setValidity();
       }
   };
});
or ngFormController:
myApp.directive("formGroup", function () {
    return {
       restrict: "A",
       require: "ngForm"
       scope: {
            input: "@"
       },
       replace: false,
       link: function (scope, elem, attrs, ngFormController) {
          //ngFormController.$setValidity();
       }
   };
});
                        If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With