如何在AngularJS中将css类添加到transcluded ng repeat内容中

How to add css class to transcluded ng-repeat content in AngularJS

本文关键字:ng transcluded repeat 添加 AngularJS 中将 css      更新时间:2023-09-26

我将问题简化为:我想生成一个myDirective指令,以便:

开发者输入:

<my-directive>
    <label ng-repeat="opt in [1,2]">
       <input type="radio" name="radio" id="opt" value="opt" ng-model="radioModel.name"> Radio {{opt}}
    </label>
</my-directive>

预期html输出:

<my-directive>
    <label class="myClass">
       <input type="radio" name="radio" id="opt" value="opt" ng-model="radioModel.name"> Radio {{opt}}
    </label>
    <label class="myClass">
      <input type="radio" name="radio" id="opt" value="opt" ng-model="radioModel.name"> Radio {{opt}}
    </label >
</my-directive>

我的问题是如何将类"myClass"动态添加到每个标签标签中?这是我的小提琴。正如你所看到的,目前我之所以能够做到这一点,是因为我手动逐个添加了每个标签标签,但我想使用ng repeat。欢迎提出任何想法/意见。

您只需要添加一个ng类。。。。

HTML

<my-directive ng-class="{'myClass':true}">
  <label>1</label>
  <label>2</label>
</my-directive>

JS

var app=angular.module('myapp', [])
.directive('myDirective', function () {
    return {
        restrict:'EA',
        transclude:true,
        template:"<div></div>",
        scope:true,
        link: function (scope, elm, attrs,ctrl,transclude) {
            transclude(scope,function(clone) {
                elm.append(clone);
            });
        }
    };
})

CSS

body {
   background-color: #eef;     
}
.myClass {
    color: red;
}

正如在小提琴中看到的。

编辑

在理解了你的问题之后,攻击它的唯一方法就是添加元素。AddClass('className'),在指令中。

var app=angular.module('myapp', [])
.directive('myDirective', function () {
    return {
        restrict:'EA',
        transclude:true,
        template:"<div></div>",
        scope:true,
        link: function (scope, elm, attrs,ctrl) {
                element.AddClass('myClass');
                $compile(element)(scope);
        }
    };
})