javascript - AngularJS 嵌套对象数组路径

标签 javascript angularjs

我有一个工厂,它进入 Controller ,我试图从 HTML 页面上的显示中获取数据。然而,我在指定对象的路径时遇到了困难。

我的工厂:

app.factory('APIMethodService', function() {
  var Head = "api.example.com";
  return {
    apis: 
    [{
      accounts: [
        {
          v1: [
            {
              uri: Head+"/v1/accounts/",
              item1: "AccountNumber",
              item2: "MoneyInAccount"
            }],
            v2: [
            {
              uri: Head+"/v2/accounts/",
              item1: "AccountNumber",
              item2: "MoneyInAccount"
            }]
        }
      ],
      customers: [
        {
          v1: [
            {
              uri: Head+"/v1/customers/",
              item1: "CustomerName",
              item2: "CustomerID",
              item3: "CustomerEmail"
            }]
        }
      ]
    }]
  };
});

我的 Controller :

app.controller('APIController', function($scope, APIMethodService) {
$scope.title = "API";
  $scope.apiList = APIMethodService;
  $scope.accountList = $scope.apiList.accounts.v1;
  $scope.accountList2 = $scope.apiList[0][0];
});

我的 HTML

<div ng-controller="APIController">

<div id="api" class="row">
  <div class="col-xs-12">
    <div class="row" style="font-size:20px">
      {{title}} Page!
      <table class="table table-striped">
        <tr ng-repeat="api in apiList | orderBy:'uri' | filter:search">
           <td>{{api.uri}}</td>
           <td>{{api.item1}}</td>
           <td>{{api.item2}}</td>
        </tr>
      </table>
    </div>
  </div>
</div>

</div>

我得到的错误与 Controller 试图解析我想要获取的单个对象有关,例如帐户客户,然后是任何版本v#,他们可能有。

所以它会说诸如

之类的内容

TypeError: Cannot read property 'v1' of undefined

我只需要一些帮助来指定进入工厂服务的正确途径。

最佳答案

您遇到一些问题。首先,您错误地引用了从工厂返回的对象。 APIMethodService 是您要注入(inject)的工厂,因此您需要首先引用该工厂返回的对象,如下所示:

APIMethodService.apis

这将为您提供整个 JSON 对象。

从那里开始,对象的其余部分由对象数组组成,因此引用“v1”不会给您带来任何好处。您需要指定一个索引。如果您想要 v1,您需要:

APIMethodService.apis[0].accounts[0].v1

这将为您提供 v1 数组,它又是一个对象数组。

客户将是:

APIMethodService.apis[0].customers[0].v1

关于javascript - AngularJS 嵌套对象数组路径,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28265925/

相关文章:

javascript - 设置 document.domain 时出现拒绝访问错误

javascript - 重置过滤数据 Vue.js

Angularjs:ng-repeat + ng-switch-when != expected

AngularJS 将页面加载到 div 中

javascript - AngularJS : How to make dynamic field button only for last button?

angularjs - 通过 angular1 ui-router 导航后,更改检测在 ng2 组件中无法正常工作

javascript - 解析来自 Socket 的 HTTP 消息

javascript - 哪种方法更适合结果集的 ListView 和 GridView

javascript - Redux 中应该在哪里进行异步操作的存储调度?

javascript - Angularjs指令点击元素