Angular - 如何将$ index传递给自定义指令?

时间:2016-12-09 18:02:15

标签: angularjs

我正在使用angular迭代集合并使用自定义指令创建多个radio按钮。我想在单击的\ checked \ selected 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>

1 个答案:

答案 0 :(得分:0)

除非必须,否则我会避免在无线电和复选框周围使用该指令,因为角度处理范围与这些对象和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成为原始范围的子项。