[英]Angular - How to pass $index to custom directive?
I'm using angular
to iterate over a collection and create using a custom directive several radio
buttons. 我正在使用
angular
遍历一个集合,并使用一个自定义指令创建了几个radio
按钮。 I want to add a certain class to a clicked\\checked\\selected radio
button. 我想将某个类添加到clicked \\ checked \\ selected
radio
按钮。 How do I pass the $index
along with the data object to the directive
? 如何将
$index
和数据对象一起传递给directive
?
This is the directive: 这是指令:
app.directive("customDirective", function () {
return {
restrict: "E",
templateUrl: "views/customDirective.html",
scope: {
choice: "="
}
}
});
This code passes the data object to the directive: 此代码将数据对象传递给指令:
<div class="row" ng-repeat="choice in questionObj.choices">
<custom-directive choice="choice"></custom-directive>
</div>
This is the guts of the directive template: 这是指令模板的内容:
<div class="radio">
<label ng-class="{choiceSelected: isChecked == $index}"><input type="radio" name="optradio" ng-model="isChecked" value="$index">{{choice.description}}</label>
</div>
Unless you have to I would avoid using the directive around radios and checkboxes because of the way that angular handles scopes with these objects and ng-repeat. 除非您必须这样做,否则我将避免在radios和checkbox周围使用指令,因为angular会使用这些对象和ng-repeat处理范围。 If you wipe out the directive and just put that html into the ng-repeat it works like this: HTML:
如果您删除指令,然后将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: 控制器:
.controller('testData', ['$scope',
function ($scope) {
$scope.selected = {};
$scope.questionObj = {
choices:[{description: 'first'},{description:'second'},{description:'third'}]
};
}])
CSS: CSS:
.choiceSelected{
color:red;
}
Here is a working plunk : https://plnkr.co/edit/JL9WOkYjRyoTLi5E7ExF?p=preview 这是一个工作的小伙伴: https ://plnkr.co/edit/JL9WOkYjRyoTLi5E7ExF ? p = preview
Also note that in the ng-repeat, the ng-model of the radio is $parent.selected. 还要注意,在ng-repeat中,收音机的ng-model是$ parent.selected。 This is because the ng-repeat causes the inner html to become a child of the original scope.
这是因为ng-repeat导致内部html成为原始范围的子级。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.