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

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

本文关键字:Angular 指令 值传 何通过 class 属性      更新时间:2023-09-26

我已经编写了以下指令,当您传递tweet的id时创建一个twitter卡片。

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似乎不允许未知标签,这是我所期望的。但是它们也不允许未知属性或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>

虽然,我不喜欢这个解决方案,我不能传递另一个属性,如主题属性。有人知道如何通过类属性传递多个变量到指令吗?

我查看了AngularJS文档,寻找通过类使用多个变量的方法,但一无所获,所以我写了一个函数来转换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();
    });

这是一个工作的活塞