AngularJS在ng-repeat中决定索引

AngularJS determining the index in ng-repeat

本文关键字:决定 索引 ng-repeat AngularJS      更新时间:2023-09-26

我想实现一个异步跟踪/取消跟踪功能。就像在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);
    });
}

实际上根本不需要任何索引,只需在函数中传递user object:

<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);
    });
}

使用$indexng-repeat中的$index为从0开始的循环的索引。

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

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