I am trying to learn angular, and I have an example code snippet that is the following:
$scope.contents = [{
name: 'Chris Doe',
abbreviation: 'Developer',
},{
name: 'Ann Doe',
abbreviation: 'Commerce',
},{
name: 'Mark Ronson',
abbreviation: 'Designer',
},{
name: 'Eric Doe',
abbreviation: 'Human Resources',
},{
name: 'John Doe',
abbreviation: 'Commerce',
},{
name: 'George Doe',
abbreviation: 'Media',
},{
name: 'Ann Ronson',
abbreviation: 'Commerce',
},{
name: 'Adam Ronson',
abbreviation: 'Developer',
},{
name: 'Hansel Doe',
abbreviation: 'Social Media',
},{
name: 'Tony Doe',
abbreviation: 'CEO',
}];
Which works fine, but I want to fetch data from an API and then load the data into the $scope.contents
. I have tried the following:
$http(req).success(function(res) {
console.log(res);
for (var i = 0; i < res.length; i++) {
console.log(res[i]);
//add data into scope contents here .add(res[i])
}
}).error(function (err) { console.log(err) });
and this works, I am able to loop through the object of data returned from my API, however I cannot figure out the syntax to add the returned data into $scope.contents
What is the proper way to do this? Is there a better way to do this? Like making $scope.contents
a class and adding the data as a new instance?
You can use Array#concat
:
$scope.contents = $scope.contents.concat(res);
Obviously you first want to make sure that $scope.contents
is already an array:
if (! Array.isArray($scope.contents)) {
$scope.contents = [];
}
$scope.contents = $scope.contents.concat(res);
$scope.contents
is an array, so you can push a new object to it.
$http(req).success(function(res) {
console.log(res);
for (var i = 0; i < res.length; i++) {
console.log(res[i]);
$scope.contents.push(res[i]);
}
}).error(function (err) { console.log(err) });
It's not obvious from your example what res[i]
contains. The above code is assuming that it is already the correct object. If not, take this and place the correct values.
$scope.contents.push({
name: res[i].name,
abbreviation: res[i].abbreviation,
}); // example -- change to match your data
$scope.contents looks like an array so...
$scope.contents.push(res[i]);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With