【问题标题】:Angular, getting index of checked checkbox (or radio) in ng-repeatAngular,在 ng-repeat 中获取选中复选框(或单选)的索引
【发布时间】:2014-10-21 10:07:23
【问题描述】:

我正在使用 ng-repeat 创建一组表单,每个表单都有一个复选框(如果重要,可能会更改为收音机),并且我正在尝试操作检查的特定级别。所以我要做的是传递复选框的索引(ng-repeat 中自身的索引。让我告诉你我的意思

<div class="saInstrcutionTableRow"  ng-repeat="parent in listTable track by $index">
                        <div class="saInstrcutionLeft"></div>
                        <!-- parent levels -->
                        <div  class="saInstrcutionCRight saInstrcutionTitle"><div class="parentSub1"> <input type="checkbox" ng-model="levelPicker">{{parent.name}}</div></div>

                        </div>

                    </div>

所以在这里我只是在 ng-model="levelPicker" 下重复输入的名称。我正在按此按钮之外的按钮,该按钮使用我设置的功能,只需要在重复中传递复选框的索引,就像这样 -

<button type="button" class="resultsButton" ng-click="submitNewSub(Checkbox index here)">Submit</button>

是否有某种角度来定位选中的复选框并在重复中获取其索引?我正在使用它在其中添加孩子。我已经尝试了一些东西,但我不确定如何直接引用它并获取它的索引(在角度范围内)。任何输入将不胜感激。谢谢!!

【问题讨论】:

  • 你试过$index吗?
  • 这个按钮在 ng-repeat 之外,所以 $index 不起作用

标签: javascript angularjs


【解决方案1】:

您可以使用类似这样的方式捕获选定的索引

<input type="checkbox" ng-change="onChange({{$index}})" ... />

onChange函数

  $rootScope.onChange = function(idx) {
    $rootScope.selectedIndex = idx;
  };

然后使用selectedIndex 来满足您的任何需求。这是quick example

【讨论】:

  • 为什么要放入 $rootScope 而不是 $scope?
  • @marneborn $scope 也可以——我刚刚使用app.run()$rootScope 创建了一个快速示例
【解决方案2】:

ng-repeat 为每个项目创建一个新范围,因此父级无法直接访问任何复选框设置的 'levelPicker'。

最正确的方法大概是这样的:

$scope.listTable = [
    { name : 'a', selected: false },
    { name : 'b', selected: false },
    { name : 'c', selected: false }
];
$scope.selectMe = function ( index, previousValue ) {
    $scope.listTable[index].selected = !previousValue;
};
$scope.submitNewSub = function () {
    for ( var i=0; i<$scope.listTable.length; i++ ) {
        console.log($scope.listTable[i].name+
            ($scope.listTable[i].selected ?
                ' is selected' :
                ' is not selected')
        );
    }
}

在 html 中有这个:

<input type="checkbox" ng-click="selectMe($index, levelPicker)" ng-model="levelPicker">{{parent.name}}

或者您可以查看所有子范围并检查它们的 levelPicker 值:

$scope.submitNewSub = function () {
    for(var cs = $scope.$$childHead; cs; cs = cs.$$nextSibling) {
        console.log($scope.listTable[cs.$index].name+
            (cs.levelPicker ?
                ' is selected' :
                ' is not selected')
        );
    }
};

【讨论】:

    猜你喜欢
    • 2015-04-10
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-09-09
    • 2014-06-10
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多