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

I have the following Angular / HTML that 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 a lot of code repetition. What I would like to do is create an Angular attribute directive that will update the div.form-group element class if the input contained in it is invalid.

This is the markup I would like to switch to:

 <div class="form-group" data-form-group data-input="editor.name"> ... </div> 

I have the following directive wrapper, but I don’t know how to control the editor.name (or input ) attribute to update the class.

 myApp.directive("formGroup", function () { return { restrict: "A", scope: { input: "@" }, replace: false, link: function (scope, elem, attrs) { } }; }); 

I suppose I need to put the appropriate code in the link function and possibly with $watch , but other than that I'm a little in the dark

+5
source share
2 answers

I got the following:

 myApp.directive("formGroup", function ($parse) { return { restrict: "A", scope: { input: "@" }, replace: false, require: "^form", link: function (scope, elem, attrs, ctrl) { var expression = [ctrl.$name, scope.input, "$invalid"].join("."); scope.$parent.$watch(expression, function (val) { alert(expression + " " + val); // Pops the value. }); } }; }); 

Note that although the expression in HTML is editor.name.$error.invalid , in the communication function it is editor.name.$invalid .

Using a form controller means that I do not need to set the ng-model attribute to <div> .

+1
source

You should use the ngModelController properties for 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(); } }; }); 
+1
source

Source: https://habr.com/ru/post/1242088/


All Articles