如何从ng-repeat获取数组项?

时间:2014-09-18 11:39:09

标签: javascript angularjs

我正在尝试在使用反向数组时获取数组项目。但得到错误的索引值。

当我点击了[7] Sebastian,他已经50岁了

<button ng-click="show_id($index)">get my id</button>

我希望警报值应为7而不是0但它会提示0

<!doctype html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <title>Example</title>



  <script src="//ajax.googleapis.com/ajax/libs/angularjs/1.3.0-rc.1/angular.min.js"></script>


<script>
angular.module("my_app",[])
.controller("my_ctr",function($scope){

    $scope.show_id=function(index){
        alert(index);
    }
})
</script>

</head>
<body ng-app="my_app" ng-controller="my_ctr">
    <div ng-init="friends = [
    {id:1, name:'John', age:25, gender:'boy'},
    {id:2, name:'Jessie', age:30, gender:'girl'},
    {id:3, name:'Johanna', age:28, gender:'girl'},
    {id:4, name:'Joy', age:15, gender:'girl'},
    {id:5, name:'Mary', age:28, gender:'girl'},
    {id:6, name:'Peter', age:95, gender:'boy'},
    {id:7, name:'Sebastian', age:50, gender:'boy'},

  ]">
    I have {{friends.length}} friends. They are:

    <ul>
      <li  ng-repeat="friend in friends.slice().reverse() ">
        [{{friend.id}}] {{friend.name}} who is {{friend.age}} years old.
        <button ng-click="show_id($index)">get my id</button>

      </li>

    </ul>
  </div>
</body>
</html>

我想编辑和更新该特定记录我该怎么做?

2 个答案:

答案 0 :(得分:2)

由于您正在寻找“当前朋友”的id,只需使用对象中提供的id

替换:

<button ng-click="show_id($index)">get my id</button>

使用:

<button ng-click="show_id(friend.id)">get my id</button>

答案 1 :(得分:-1)

当你在列表的反面迭代时,你无法获得原始列表的索引

得到你需要使用下面的

ng-click="show_id(friends.length-$index)"