helloMundo helloMundo - 5 months ago 30
AngularJS Question

Calling a function in ng-repeat?

If I had some code similar to this, how would I go about calling the

getUserName()
function inside the ng-repeat. I attempted to do it earlier and it worked, however, it no longer functions.

var user_reviews = [
{
user:{
name: "John Doe"
},
review:{
item: "Shure SE215"
}
}
]

var app = angular.module("ExApp", []);
app.controller("TestController", function($scope){
$scope.reviews = user_reviews;
$scope.getUserName = function(){
return $scope.user.name;
}
});


HTML

<div ng-controller="TestController">
<div ng-repeat="review in reviews">
<p>{{review.getUserName()}}</p>
</div>
</div>

Answer

Assuming scope.getUserName() isn't as trivial as it is in your example, you can do this instead.

    // Pass the `review` object as argument
    $scope.getUserName = function(review){
        return review.user.name; // get the user name from it
    }

HTML, pass review as parameter

<div ng-controller="TestController">
  <div ng-repeat="review in reviews">
    <p>{{getUserName(review)}}</p>
  </div>
</div>