简体   繁体   中英

AngularJS determining the index in ng-repeat

I'm trying to implement an asynchronous follow/unfollow function.. just like in instagram when you pull up the list of your followers there's an 'following'/'follow' button associated to each item.. for brevity i made the code simple. I'm using ionic framework

my code in the view:

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

}

You don't really need any index at all, just pass user object in the function:

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

And use it this way:

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

So your code becomes cleaner and simpler.

Use $index . $index inside the ng-repeat is the index of the loop starting from zero.

iterator offset of the repeated element (0..length-1)

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM