我将我的问题简化如下:我想制作一个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”添加到每个标签标签?这是my jsfiddle。如您所见,目前我能够这样做,因为我手动逐个添加每个标签标签,但我想使用ng-repeat代替。任何想法/意见都表示赞赏。
答案 0 :(得分:1)
你只需添加一个ng-class ....
<强> 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;
}
如小提琴here中所见。
在理解了你的问题之后,攻击它的唯一方法是在指令中添加element.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);
}
};
})