我正在使用angular遍历一个集合,并使用一个自定义指令创建几个radio按钮。我想将某个类添加到单击\选中\选中的radio按钮。如何将$index与数据对象一起传递给directive
这是一条指令:
app.directive("customDirective", function () {
return {
restrict: "E",
templateUrl: "views/customDirective.html",
scope: {
choice: "="
}
}
});此代码将数据对象传递给指令:
<div class="row" ng-repeat="choice in questionObj.choices">
<custom-directive choice="choice"></custom-directive>
</div>这是指令模板的核心:
<div class="radio">
<label ng-class="{choiceSelected: isChecked == $index}"><input type="radio" name="optradio" ng-model="isChecked" value="$index">{{choice.description}}</label>
</div>发布于 2016-12-10 03:06:49
除非您必须这样做,否则我会避免使用radios和复选框周围的指令,因为angular使用这些对象和ng-repeat处理作用域的方式。如果您删除该指令并将该html放入ng-repeat中,则它的工作方式如下: HTML:
<div class="row" ng-repeat="choice in questionObj.choices">
<div class="radio">
<label ng-class="{choiceSelected: selected == choice.description}">
<input type="radio" name="{{choice.description}}" ng-model="$parent.selected" ng-value="choice.description">
{{choice.description}}
</label>
</div>控制器:
.controller('testData', ['$scope',
function ($scope) {
$scope.selected = {};
$scope.questionObj = {
choices:[{description: 'first'},{description:'second'},{description:'third'}]
};
}])CSS:
.choiceSelected{
color:red;
}这是一个有效的方法:https://plnkr.co/edit/JL9WOkYjRyoTLi5E7ExF?p=preview
还要注意,在ng-repeat中,无线电的ng-model是$parent.selected。这是因为ng-repeat会导致内部html成为原始作用域的子级。
https://stackoverflow.com/questions/41066308
复制相似问题