Angular apply class in directive

五迷三道 提交于 2020-01-30 08:36:24

问题


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?


回答1:


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



来源:https://stackoverflow.com/questions/31502421/angular-apply-class-in-directive

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!