替换为true时合并ngClass属性 [英] merge ngClass attributes when replace true

查看:82
本文介绍了替换为true时合并ngClass属性的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这是我的指令,替换:true 在指令定义上设置

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

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

这是指令模板

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

现在,如果按照以下方式使用my指令,则会抛出错误

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

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

原因是,因为模板还定义了 data-ng-class 属性,发出的HTML如下

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 ,查看浏览器控制台中的错误消息并检查元素以检查 data-ng-class 属性

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

推荐答案

我看到有一个打开问题谈论这个。

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

您可以使用编译在链接功能之前修改表达式触发。 Plunkr

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;
        };

      };
    }
  };
});

这篇关于替换为true时合并ngClass属性的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆