How to add Angular for each element in one array

Here I would like to clearly explain my problem.

$http.get('arealist.json').success(function(response){
      angular.forEach(response, function(data){
           $scope.arealist = data.area_name;
           console.log($scope.arealist);
      });
});

Using the code above, I get the scope name from isalist.json. and it looks like the image below on the console. console.log image

but I need to store the data above in an array and it looks below

$scope.arealist = [ 
                    "Avadi", 
                    "Poonamallee",
                    "Padi", 
                    "Ambattur Industrial Estat",
                    "Annanagar",
                    "Arumbakkam",
                    "Kodambakkam",
                    "Nandanam"
                  ]

How can i do this?

+4
source share
4 answers

Declare a variable as shown below.

var arealistArray=[];
$scope.arealist=[]; 

Then enter the value into the array.

angular.forEach(response, function(data){
       arealistArray.push(data.area_name);
  });

Finally, assign an array to the scope variable.

$scope.arealist=arealistArray;
+2
source

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);
      });
});
+1
source

, ( $scope )? , , . :

angular
    .module(/*module name*/)
    .service('AreaService', function ($http) {

        // Map the array of area objects to an array
        // of each area object `area_name` property
        this.getAreas = function () {
            return $http
                .get('arealist.json')
                .then(function (response) {
                    return response.data.map(function (data) {
                        return data.area_name;
                    });
                });
        };
    })

:

    .controller(/*controller name*/, function (AreaService) {
        AreaService.getAreas().then(function (areas) {
            $scope.arealist = areas;
        }); 
    });
+1

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;
    });
});

Browser support for maps.

If you use 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;
    });
});
0
source

Source: https://habr.com/ru/post/1624745/


All Articles