merge ngClass attributes when replace true

喜你入骨 提交于 2019-12-08 02:37:59

问题


Here is my directive which has replace: true set on directive definition

<my-custom-tag>
</my-custom-tag>

this is the directive template

<div data-ng-class="{'class1': condition1, 'class2': condition2}">
</div>

Now if the use my directive as follows it throws up error

<my-custom-tag data-ng-class="{'class3': condition3}"></my-custom-tag>

The reason being, since the template also defines a data-ng-class attribute, the emitted HTML is as follows

<div data-ng-class="{'class3': condition3} {'class1': condition1, 'class2': condition2}"></div>

Hence the syntax error while compiling template. Any way to merge these objects ?

Plunkr, look at the browser console for the error message and inspect element to check the data-ng-class attribute


回答1:


I saw that there is a open issue talking about this.

You can use compile to modify the expression before the link function is triggered. Plunkr.

angular.module('directive', []).directive('myCustomTag', function() {
  return {
    template: "<div data-ng-class=\"{'foo': whenFoo()}\">My Custom Tag</div>",
    restrict: 'E',
    replace: true,
    compile: function compile(tElement, tAttrs) {

      tAttrs.ngClass = tAttrs.ngClass.replace(/}\s*{/g, ', ');

      return function (scope, iElement, iAttrs) {
        scope.whenFoo = function() {
          return true;
        };

      };
    }
  };
});


来源:https://stackoverflow.com/questions/30440194/merge-ngclass-attributes-when-replace-true

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