Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to Write an Angular directive to update CSS class based on form validation

Tags:

css

angularjs

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

like image 701
Graham Avatar asked Oct 31 '22 10:10

Graham


1 Answers

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();
       }
   };
});
like image 129
Stepan Suvorov Avatar answered Nov 14 '22 18:11

Stepan Suvorov