Nicho Nicho - 5 months ago 13
AngularJS Question

(newbie) Get data from array of objects using ng-repeat and for loop

I have to access some objects inside an array:

.success(function(data) {
$scope.activities = data.result[0].attributes
});


And I can access this particular index, as expected, inside my view with

<div ng-repeat="x in activities">
<p>{{x.name}}: {{x.value}}</p>
</div>


Now obviously, this only returns the first object in the array, at index 0. (Right?). So I figure I have to somehow loop the function..

.success(function(data) {
for(var i = 0; i < data.result.length; i++) {
$scope.activities = data.result[i].attributes;
}
});


As far as I can tell, the actual for loop is working.. but I need help in the next step exposing this to my view.

Here is my plunker: https://plnkr.co/edit/2ZukY3Oq8vYvghfCruHx?p=preview

(although the data is not available, I have added what the response looks like in the comments)

Answer

As per my understanding of your issue, you can solve it by using two ng-repeat clauses.

Your controller code,

.success(function(data) { 
    $scope.ativitiesArray = data.result; 
});

Your html code,

<div ng-repeat="activities in activitiesArray track by $index">
    <div ng-repeat="x in activities.attributes track by $index">
        <p>{{x.name}}: {{x.value}}</p>
    </div>
</div>

I've added track by $index phrase to ng-repeat as it will increase performance. Also, as per suggestions in the comments, please avoid using .success(). It is recommended to use .then().

Hope this solves the issue.