Reputation: 137
Here i like to explain my problem clearly.
$http.get('arealist.json').success(function(response){
angular.forEach(response, function(data){
$scope.arealist = data.area_name;
console.log($scope.arealist);
});
});
Using the above code am getting area_name from arealist.json. and it looks like below image in console.
but i need the store above data in a array and it look like below
$scope.arealist = [
"Avadi",
"Poonamallee",
"Padi",
"Ambattur Industrial Estat",
"Annanagar",
"Arumbakkam",
"Kodambakkam",
"Nandanam"
]
How can i do this ?
Upvotes: 6
Views: 29446
Reputation: 27217
It looks like you are performing this request within a controller (as $scope
is available)? So first of all, you should be doing requests like this within a service. For example:
angular
.module(/*module name*/)
.service('AreaService', function ($http) {
// Map the array of area objects to an array
// of each area object's `area_name` property
this.getAreas = function () {
return $http
.get('arealist.json')
.then(function (response) {
return response.data.map(function (data) {
return data.area_name;
});
});
};
})
And then consume the service within your controller:
.controller(/*controller name*/, function (AreaService) {
AreaService.getAreas().then(function (areas) {
$scope.arealist = areas;
});
});
Upvotes: 1
Reputation: 8040
You can use Array.prototype.map() to achieve this.
$scope.arealist = [];
$http.get('arealist.json').success(function (response) {
$scope.arealist = response.map(function (data) {
return data.area_name;
});
});
If you are using libraries like underscore.js or lodash, use _.map() for the same result.
$scope.arealist = [];
$http.get('arealist.json').success(function (response) {
$scope.arealist = _.map(response, function (data) {
return data.area_name;
});
});
Upvotes: 0
Reputation: 544
Declare a variable like below.
var arealistArray=[];
$scope.arealist=[];
Then push a value into array.
angular.forEach(response, function(data){
arealistArray.push(data.area_name);
});
Finally Assign the array to scope variable.
$scope.arealist=arealistArray;
Upvotes: 4
Reputation: 8971
Use an array:
$scope.arealist = [];
$http.get('arealist.json').success(function(response){
angular.forEach(response, function(data){
$scope.arealist.push(data.area_name);
console.log($scope.arealist);
});
});
Upvotes: 1