繁体   English   中英

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

[英]Angular - How to pass $index to custom directive?

我正在使用angular遍历一个集合,并使用一个自定义指令创建了几个radio按钮。 我想将某个类添加到clicked \\ 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>

除非您必须这样做,否则我将避免在radios和checkbox周围使用指令,因为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成为原始范围的子级。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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