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

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

问题描述

这是我的指令,它在指令定义上设置了 replace: true

</my-custom-tag>

这是指令模板

现在,如果使用我的指令如下,它会抛出错误

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

原因是,由于模板还定义了一个 data-ng-class 属性,因此发出的 HTML 如下

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

因此编译模板时出现语法错误.有没有办法合并这些对象?

Plunkr,查看浏览器控制台的错误信息并检查元素data-ng-class 属性

解决方案

我看到有一个未解决的问题 谈论这个.

您可以在触发链接函数之前使用compile来修改表达式.Plunkr.

angular.module('directive', []).directive('myCustomTag', function() {返回 {模板:"<div data-ng-class=\"{'foo': whenFoo()}\">我的自定义标签</div>",限制:'E',替换:真的,编译:函数编译(tElement,tAttrs){tAttrs.ngClass = tAttrs.ngClass.replace(/}\s*{/g, ', ');返回函数(范围,iElement,iAttrs){scope.whenFoo = function() {返回真;};};}};});

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

解决方案

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

      };
    }
  };
});

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

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