简体   繁体   中英

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. I want to add a certain class to a clicked\\checked\\selected radio button. How do I pass the $index along with the data object to the 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. If you wipe out the directive and just put that html into the ng-repeat it works like this: 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:

.choiceSelected{
  color:red;
}

Here is a working plunk : https://plnkr.co/edit/JL9WOkYjRyoTLi5E7ExF?p=preview

Also note that in the ng-repeat, the ng-model of the radio is $parent.selected. This is because the ng-repeat causes the inner html to become a child of the original scope.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM