获取angularjs中数组的父索引

时间:2015-02-03 02:16:01

标签: html angularjs

我在控制器中有一些scope.students数组。并且数据在表格中使用ng-repeat以我的视图形式显示。我现在要做的是当我点击按钮时,它应该警告特定对象的父索引。例如,我单击1 Brick Med的按钮然后它应该警告0,因为他在A部分。然后当我点击3中的按钮时它应该警告1,因为他是sectionB。我是angularjs的新人,任何帮助都是数百万赞赏谢谢

var stud = angular.module("stud", []);
stud.controller("StudentsController", function ($scope) {
	'use strict';
  
  
    $scope.alertMe = function (key){
     alert(0);
    };  

    $scope.sectionA = [
      {
        no:1,
        name:'Brick Med',
      },
      {
        no:2,
        name: 'Colin Christopher',
      },
    ];
      
     $scope.sectionB = [
      {
        no:3,
        name: 'Frank Joemar Timbang',
      },
      {
        no:4,
        name: 'Curtis Zaymond',
      }
      ];
    
    $scope.students = [
      $scope.sectionA,
      $scope.sectionB
    ];

    	

});
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<!DOCTYPE html>
<html data-ng-app="stud">
<head lang="en">
	<meta charset="utf-8">
	<title>Tally Boxes</title>
</head>
<body data-ng-controller="StudentsController" data-ng-init="init()">
  <div id="container">
   </div>
  <div class="container-table">
    <table border="1" width="100%">
        <thead>
            <tr>
                <td>Students</td>
                <td>Alert</td>
            </tr>
        </thead>
        <tbody>
            <tr ng-repeat="(key,value) in students[0]">
                <td>{{value.no}} {{value.name}}</td>
              <td><button ng-click="alertMe(key)">Alert me!</button></td>
                 
            </tr>
           <tr ng-repeat="(key,value) in students[1]">
                <td>{{value.no}} {{value.name}}</td>
              <td><button ng-click="alertMe(key)">Alert me!</button></td>
                 
            </tr>
        </tbody>
</table>
</div>

  <script src="angular.min.js"></script>  
  <script src="tallyboxController.js"></script>
  <script src="tallyboxDirective.js"></script>


</body>
</html>

1 个答案:

答案 0 :(得分:2)

你的ng-repeat有点乱,但我猜这就是你想做的事情:

<tbody ng-repeat="studentGroup in students">
    <tr ng-repeat="student in studentGroup">
        <td>{{student.no}} {{student.name}}</td>
        <td><button ng-click="alertMe($parent.$index)">Alert me!</button></td> 
    </tr>
</tbody>

请注意,(key, value)用于迭代对象的属性,但students是一个数组。

对于$parent.$index,请参阅Access index of the parent ng-repeat from child ng-repeat

对于tbody ng-repeat,请参阅How to use ng-repeat without an html element


您可以通过将$parent.$index更改为ng-clickalertMe(studentGroup)更改为

来避免使用$scope.alertMe
$scope.alertMe = function (studentGroup) {
    alert($scope.students.indexOf(studentGroup));
};

但这取决于你最后的用法,你更喜欢哪一个。