AngularJS确定ng-repeat中的索引

时间:2015-07-15 06:42:12

标签: javascript angularjs ionic-framework

我正在尝试实现异步关注/取消关注功能..就像在Instagram中拉出关注者列表时,每个项目都有一个“跟随”/“关注”按钮...为了简洁我做了代码简单。我正在使用离子框架

我在视图中的代码:

<ion-list>
    <ion-item ng-repeat="user in users">
        <span ng-click="followUser(user.id, indexHowTo??)">Follow</span>
        <p>{{user.name}}</p>
    </ion-item>
</ion-list>
$scope.followUser = function(userid, indexHowTo) {

    var to_from = {
        to_user: userid,
        from_user: $localStorage.CurrentUser.id
    }
    UserService.FollowUser(to_from, $localStorage.CurrentUser.auth_token)
        .success(function(data) {
            $scope.users[index].is_following = true; //i'll do something in the view just didn't show for brevity

        }).
    error(function(error, status) {
        //alert(status);
        console.log(error);
    });

}

2 个答案:

答案 0 :(得分:3)

你根本不需要任何索引,只需在函数中传递用户对象:

<ion-list>
  <ion-item ng-repeat="user in users">   
    <span ng-click="followUser(user)">Follow</span>
    <p>{{user.name}}</p>
  </ion-item>
</ion-list>

并以这种方式使用它:

$scope.followUser = function (user) {

    var to_from = {
        to_user: user.id,
        from_user: $localStorage.CurrentUser.id
    };

    UserService.FollowUser(to_from, $localStorage.CurrentUser.auth_token)
    .success(function (data) {
        user.is_following = true;
    }).
    error(function (error, status) {
        //alert(status);
        console.log(error);
    });
}

因此,您的代码变得更清晰,更简单。

答案 1 :(得分:2)

使用$index$index内的ng-repeat是从零开始的循环索引。

  

重复元素的迭代器偏移量(0..length-1)

<span ng-click="followUser(user.id, $index)"
<!--                                ^^^^^^^ -->