ibrahim morsi blacktiger ibrahim morsi blacktiger - 4 months ago 9
AngularJS Question

Angularjs why for/loop overriding the array items

I'm trying to use twitch api and I need to know which user is online

//Initialize the App
var channels = ["ESL_SC2", "OgamingSC2", "cretetion", "freecodecamp", "storbeck", "habathcx", "RobotCaleb", "noobs2ninjas"];
var app = angular.module('Twitch', []);

//main controller

app.controller("MainController", function ($scope, $http) {

//Where controller variables are assigned

// create the game Object
var result = {};
$scope.results = [];
var stream = {};
var care = "";
$scope.streams = [];
var url = 'https://api.twitch.tv/kraken/channels/';

for (var x = 0; x < channels.length; x++) {

$http.jsonp(url + channels[x] + '?callback=JSON_CALLBACK').success(function (data) {
result = data;
var id = data._id;
var name = data.name;

$scope.url = "http://static-cdn.jtvnw.net/jtv_user_pictures/" + name + "-profile_image-" + id + "-300x300.jpeg";
$scope.image = data.logo;
$scope.name = data.name;
$scope.status = data.status;

$http.jsonp("https://api.twitch.tv/kraken/streams/" + channels[x] + "?callback=JSON_CALLBACK").success(function (data) {
var streaming = (data.stream === null) ? false : true;
if (streaming) {
result.off = 'online';
var streamTitle = data.stream.channel.status;

if (streamTitle.length > 36) {
streamTitle = streamTitle.substring(0, 33);
streamTitle += '...';
}
result.streamTitle = streamTitle;
} else {
result.off = 'offline';
data.streamTitle = '';
}
result.username = channels[x];
});

$scope.results.push(result);

console.log(result);
}).error(function (data) {
// something went wrong :(
console.log('Got nothing');
});
}
});


I created variable which is
result.off
to hold the status value for the user

(online/offline)
and i'm showing this values inside table

<div class="container text-center text-middle" ng-controller='MainController'>
<table class="table" ng-repeat="result in results">
<tbody>
<tr ng-class="satus">
<td><a class="media-left" href="#">
<img ng-src={{result.logo}} alt="image" class="img-circle img-middle " width='50px'> </a></td>
<td>
<h4 class="media-heading">{{result.name}} <span class="label"><p>{{result.off}}</p></span></h4>
</td>
<td><h4>{{result.status}}</h4></td>
</tr>
</tbody>
</table>
</div>


the expression result.off only shows the last user status in the list

Answer

Try to move the result variable inside the for - loop

when you do result = data; you just overwrite the value and push it.

The resulting array is a list of the same object

Comments