获取数组angularjs的父索引

时间:2015-02-17 06:26:11

标签: html angularjs

我搜索,我发现这个代码是我现在需要的。但它有些不对劲。当我点击alertme按钮时,它的警报是-1,这是错误的。当我点击1 Brick med它的警报-1时它应该是0,因为no和name在sectionA中。当我想点击3 Frank Joemar Timbang时,它应该提醒1,因为他在B部分?阿尼有帮助吗?建议? TIA



var stud = angular.module("stud", []);
stud.controller("StudentsController", function ($scope) {
	'use strict';
  
  
  $scope.alertMe = function (studentGroup) {
    alert($scope.students.indexOf(studentGroup));
};
    $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>Students</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 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>
</table>
</div>
</body>
</html>
&#13;
&#13;
&#13;

2 个答案:

答案 0 :(得分:2)

好的,你的问题是当你想使用studentGroup作为索引时,你正在使用indexOf()。

$scope.alertMe = function (studentGroup) {
     alert($scope.students[studentGroup]); // returns object object in your array
     alert($scope.students[studentGroup][0]); /// returns sectionA object1
     alert($scope.students[studentGroup][0].name); /// returns sectionA object1 name
};

我修复了你的HTML,因此它更容易阅读,但你原来的东西应该仍然有用。

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

如果这不是你想要的,你真的想提醒索引,让我解释一下indexOf的工作原理。该方法将采用搜索参数,并用于在数组中搜索该元素数据。它现在返回-1,因为你给它索引,它搜索索引作为索引0和1中的元素数据。步骤:无论索引= $ scope.sectionA,Nope继续,是否索引= $ scope .sectionB,nope继续前进。完成后,未找到搜索参数返回-1。

答案 1 :(得分:1)

问题在于indexOfstudentGroup正确设置为0,前两行为1$scope.alertMe = function (studentGroup) { alert($scope.students[studentGroup]); }; 为下一个2.如果需要剖面数组,则应使用

{{1}}