Daniel Santos
Daniel Santos

Reputation: 1458

How to create a Attribute Directive to insert another attribute directive in a element in AngularJS

I'm using CSS classes from Bootstrap to highlight fields with errors, like so:

<div class="form-group" ng-class="{'has-error': $ctrl.form.name.$invalid && $ctrl.form.name.$touched}">
    <label for="name">Name</label>
    <input type="text" id="name" name="name" class="form-control" ng-model="$ctrl.client.name">
</div>

I don't want to repeat that same ng-class attribute for every field, so I'm trying to create an Attribute Directive, where I can specify the field and let angular generate the ng-class:

<div class="form-group" has-error="$ctrl.form">

But I can't get angular to compile the 'new' ng-class:

 angular.module('myApp').directive('hasError', ($compiler)=> {
    return {
        restrict: 'A',
        compile: (element) => {
            var fieldExpression = element.attr('has-error');
            element.attr('ng-class', `{\'has-error\': ${fieldExpression}.$touched && ${fieldExpression}.$invalid }`);
            element.removeAttr('has-error');
            compilerService(element);
        }
    }
});

Upvotes: 0

Views: 28

Answers (1)

georgeawg
georgeawg

Reputation: 48948

Instead of adding and compiling an ng-class directive, simply compute and manipulate the classes in the link function directly:

app.directive('hasError', () => {
    return {
        restrict: 'A',
        link: (scope,elem,attrs) => {
            scope.$watch(
               () => {
                  let expn = scope.$eval(attrs.hasError);
                  return expn && expn.$touched && expn.$invalid;
               },
               (value) => {
                    elem.removeClass('has-error');
                    value && elem.addClass('has-error');
               }
            );
        }
    }
});

Upvotes: 1

Related Questions