【问题标题】:Angular load local json and get arrays角度加载本地 json 并获取数组
【发布时间】:2015-08-20 20:39:22
【问题描述】:

我是 angular 新手,我正在尝试加载 json 文件并在索引文件上重复它,但可以通过该 json 来获取重复的数组

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 文件

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

我想得到名称和城镇,任何想法如何通过 data-> customer_list 直到我得到类似的东西:

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

【问题讨论】:

    标签: json angularjs


    【解决方案1】:

    你可以使用内置的map函数:

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

    map() 方法使用调用的结果创建一个新数组 在此数组中的每个元素上提供函数。

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

    【讨论】:

      【解决方案2】:

      t您可以使用ng-repeat 显示名称和城镇循环槽content.data.customers_list

      控制器:

      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>
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2017-10-17
        • 2020-04-12
        • 2019-03-04
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2023-03-18
        相关资源
        最近更新 更多