johnny04501
johnny04501

Reputation: 279

Angular load local json and get arrays

I am new in angular and I am trying to load json file and repeat it on index file but can get through that json to get the arrays for repeat

app.js

chatApp.controller('userCtrl', function ($scope, $filter, $http) {

 var obj = {content:null};

$http.get('test.json').success(function(data) {

    obj.content = data;
});    
console.log(obj);});

json file

{"data":
{"result":"success","customers_list":[
{"Chat":
{
    "name": "John",
    "town":"LA"
}},
{"Chat":
{
    "name": "Peter",
    "town":"NY"
}}],"message":"The function is correctly"}}

I would like to get the name and town , any ideas how to go through data-> customer_list untill I get something like:

$scope.loadChat =[ 
 {
        "name": "John",
        "town":"LA"
  },
  {
        "name": "Peter",
        "town":"NY"    
}
];

Upvotes: 1

Views: 786

Answers (2)

wallek876
wallek876

Reputation: 3259

tYou can display the name and town looping trough content.data.customers_list with ng-repeat.

controller:

chatApp.controller('userCtrl', ['$scope', '$http', function($scope, $http) {
  $http.get('test.json').success(function(data) {
    $scope.content = data;
  });
}]);

html:

<div ng-repeat="user in content.data.customers_list">
  {{user.Chat.name}} {{user.Chat.town}}
</div>

Upvotes: 0

oznu
oznu

Reputation: 1694

You can use the built in map function:

chatApp.controller('userCtrl', function ($scope, $filter, $http) {
  $scope.loadChat = [];

  $http.get('test.json').success(function(data) {
     $scope.loadChat = data.data.customers_list.map(function(chat) {
         return chat.Chat;
     });
  });

});

The map() method creates a new array with the results of calling a provided function on every element in this array.

https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Global_Objects/Array/map

Upvotes: 2

Related Questions