2

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

}
2
  • <ion-item ng-repeat="user in users track by $index"> try this. Commented Jul 15, 2015 at 6:48
  • It is recommended that you pass the reference of the array item rather than passing the $index. Using the $index may pose problems if you use filters in your ng-repeat statement. Commented Jul 15, 2015 at 6:57

2 Answers 2

3

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.

Sign up to request clarification or add additional context in comments.

Comments

2

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)"
<!--                                ^^^^^^^ -->

3 Comments

could you please show how you put the index in the ng-repeat
@teddybear123 See the highlighted code in the above snippet.
just be careful. If you use an sort by it will change the index's. The $index represents the index of the currently rendered items. If you want a true index you may need to add a index to the data items themselves in the array

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.