如何通过 class 属性将值传递给 Angular 指令?

How to pass a value to an Angular Directive through the class attribute?

我编写了以下指令,当您传递推文的 ID 时会创建一张推特卡片。

angular.module('app')
     .directive('tweetCard',function () {
          return {
            transclude:true,
            template: '<ng-transclude></ng-transclude>',
            restrict: 'AEC',
            controller:function($scope, $element, $attrs){
               twttr.widgets.createTweet($attrs.tweetId,$element[0], 
                   {theme:$attrs.theme?$attrs.theme:'light'})
                   .then(function(){
                       $element.find('ng-transclude').remove();
                   });
            }
     };
});

如果我按下面的方式使用该指令,它会非常有效。

<tweet-card tweet-id="639487026052644867"></tweet-card>
<div tweet-card tweet-id="639487026052644867"></div>

尽管如此,我创建此指令的原因是我可以将此标签放入我的 wordpress.com 博客中。 尝试之后,似乎 wordpress 不允许使用未知标签,这是我所预料的。 但它们也不允许 post 中的未知属性或 data-* 属性。 所以我尝试将所有内容都放在 class 属性中,如下所示。

<div class="tweet-card tweet-id:639526277649534976;"></div>

不幸的是,这不起作用,我尝试摆弄它。 我可以扩展指令以检查 tweetCard 属性是否包含这样的 id。

angular.module('app')
     .directive('tweetCard',function () {
          return {
            transclude:true,
            template: '<ng-transclude></ng-transclude>',
            restrict: 'AEC',
            controller:function($scope, $element, $attrs){
               var id = $attrs.tweetId?$attrs.tweetId:$attrs.tweetCard;
               twttr.widgets.createTweet(id,$element[0],
                   {theme:$attrs.theme?$attrs.theme:'light'})
                   .then(function(){
                       $element.find('ng-transclude').remove();
                   });
            }
     };
});

与以下html.

<div class="tweet-card:639526277649534976;"></div>

不过,我不喜欢这种解决方法,而且我不能传递另一个属性,如 theme 属性。 有人知道如何通过 class 属性将多个变量传递给指令吗?

我查看了 AngularJS 文档,寻找通过 class 使用多个变量的方法,但一无所获,所以我编写了一个函数来转换 class 语法中的名称 angular 读取。 (<span class="my-dir: exp;"></span>) 对象。

function classNameToObj(className) {
    //different attributes are separated by semicolons
    var attributes = className.split(';');
    var obj = {};
    for (var i = 0; i < attributes.length; i++) {
        var attribute = attributes[i];
        //key-values separated by colon
        var splittedAttr = attribute.split(':');
        obj[splittedAttr[0].trim()] = splittedAttr[1].trim();
    }
    return obj;
}

这样您的 HTML 就可以同时传递推文 ID 和主题:

<div class="tweet-card:639526277649534976; theme:dark"></div>

您的指令可以像这样创建小部件:

var id = $attrs.tweetCard;
var attributes = classNameToObj($attrs.class);
var theme = attributes.theme;
twttr.widgets.createTweet(id, $element[0], {
        theme: theme || 'light'
    })
    .then(function() {
        $element.find('ng-transclude').remove();
    });

这是一个有效的 plunkr