Search code examples
javascriptangularjsangularjs-directivedom-manipulationangularjs-ng-class

Angular apply class in directive


I have a angular directive which will produce bootstrap form-group, looks for $scope.errors for value of ng-model of the directive to show errors.. Example below: My html code:

<input type="text" b-input ng-model="data.company.name" label="Company Name" class="form-control"/>

and my directive code:

app.directive('bInput', function ($compile) {
    return {
        restrict: 'EA',
        replace: true,
        link: function (scope, element, attrs) {
            var div = $('<div>', {
                'class': 'form-group',
                'ng-class': " 'has-error' : errors." + attrs.ngModel + " != null "
            });

            $compile(div)(scope);
            element.wrap(div);
            if (attrs.label != undefined) {
                element.before('<label for="' + attrs.name + '" class="control-label">' + attrs.label + '</label>');
                element.removeAttr('label');
            }
        }
    };
});

Can you please explain me how do i achieve the desired result?


Solution

  • Modify element inside the compile fn of the directive because at DOM is plain. and then recompile that element inside the link function which is return from compile function.

    Code

    app.directive('bInput', function($compile) {
      return {
        restrict: 'EA',
        replace: true,
        compile: function(element, attrs) {
          var div = $('<div>', {
            'class': 'form-control',
            'ng-class': " 'has-error' : errors." + attrs.ngModel + " != null "
          });
          element.wrap(div);
          if (attrs.label != undefined) {
            element.before('<label for="' + attrs.name + '" class="control-label">' + attrs.label + '</label>');
            element.removeAttr('label');
          }
          element.removeAttr('b-input');
          return function(scope, element, attrs) {
            var linkFn = $compile(element);
            linkFn(scope)
          }
        };
      });
    

    Look at similar SO answer here