Reputation: 87
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>
Upvotes: 0
Views: 7342
Reputation: 1465
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>
Upvotes: 2
Reputation: 387
You should change your code to this.
<div ng-controller="TestController"><div ng-repeat="review in reviews">
<p ng-repeat="userName in review.getUserName(review.name)">{{userName.name}}</p></div></div>
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(userName){
return $scope.user.name;
}
});
Upvotes: 0
Reputation: 528
//You can directly access the username
<div ng-controller="TestController">
<div ng-repeat="review in reviews">
<p>{{review.user.name}}</p>
</div>
</div>
//or You can pass the review as parameter and return username from that function.
//HTML
<div ng-controller="TestController">
<div ng-repeat="review in reviews">
<p>{{getUserName(review)}}</p>
</div>
</div>
//JS
$scope.getUserName = function(review){
return review.user.name;
}
Upvotes: 1
Reputation: 41387
You can pass the index from ng-repeat and return the user.name relevant to that index
<div ng-controller="TestController">
<div ng-repeat="review in reviews">
<p>{{getUserName($index)}}</p>
</div>
</div>
var app = angular.module("ExApp", []);
app.controller("TestController", function($scope){
$scope.reviews = user_reviews;
$scope.getUserName = function(index){
return $scope.reviews[index].user.name;
}
});
but if you are using function for this senario only i prefer do it without the function like this
<div ng-controller="TestController">
<div ng-repeat="review in reviews">
<p>{{review.user.name}}</p>
</div>
</div>
Upvotes: 4