【问题标题】:AnjularJS Controller not working with ng-repeatAngularJS 控制器不使用 ng-repeat
【发布时间】:2014-04-15 02:47:03
【问题描述】:

我正在尝试使用一个控制器为一个表生成两个对象。控制器如下所示:

function LineItemController($scope, $http) {
  $scope.fields = [{id: 0}];
  $scope.addNewChoice = function() {
    $scope.fields.push({id: ($scope.fields.length)});
  }
  $scope.lineItems = [];
  $scope.getlineItems = function() {
    $http.get('<%= line_items_path(:json) %>?invoice_id=<%= params[:id] %>').then(function(lineItems) {
      console.log(lineItems);
      return $scope.lineItems;
    });
  };
 $scope.lineItems = $scope.getlineItems();
};

HTML如下:

<div ng-controller="LineItemController">
<table>
  <thead><th>Quanity</th><th>Description</th><th>Price Per</th><th>Discount</th><th>Line Item Total</th></thead>
      <tr ng-repeat="lineItem in lineItems">
        <td>{{ lineItem.name }}</td>
        <td>{{ lineItem.quantity }}</td>
    </tr>
  <tr ng-repeat="field in fields">
 ....
</tr>
</table>

第二个 ng-repeat 工作正常。第一个似乎没有遍历对象。我检查了控制台,并使用 http get 请求正确地拉入了阵列。如果我预先填充以读取 $scope.lineItems = [{"name": 15, "quantity": 12 }];它将能够调用 15 和 12。所以我认为我的代码中的故障是调用该函数并将其设置为等于 $scope.lineItems。在调用我缺少的函数时是否需要包含其他 [] 或 {}。我正在使用 rails 4,但禁用了 turbolinks。

【问题讨论】:

    标签: javascript angularjs ruby-on-rails-4


    【解决方案1】:

    首先,您的函数 $scope.getlineItems 似乎没有返回任何内容。

    此外,$http.get 方法将返回一个承诺,因此您不想将它直接分配给您的 $scope.lineItems 变量。相反,在then 回调中,将您的数据分配给$scope.lineItems

    $scope.getlineItems = function() {
        $http.get('<%= line_items_path(:json) %>?invoice_id=<%= params[:id] %>').then(function(lineItems) {
          console.log(lineItems);
          $scope.lineItems = lineItems;
        });
      };
     $scope.getlineItems();
    

    【讨论】:

    • 似乎为 {{ lineItem.name }} 和 {{ lineItem.quantity }} 返回空白,而不是数组的值。我可以在结果应该是但没有值的地方出现差距。获取请求正在返回一个对象。不确定我是否完全理解你的第一句话
    • 正如你所拥有的, $scope.getlineItems 不会返回任何东西......回调返回一个没有任何东西可以访问的值。此外,您不能只返回 $http.get ,因为该函数的结果是一个承诺对象,而不是您的实际数据数组。为了测试,使用静态数组设置回调设置 $scope.lineItems。
    • 将 $scope.lineItems = 设置为数组似乎有效。我添加到您的脚本中的更改使其成为 lineItems.data,这似乎有效!还在函数之前添加了一个空白 $scope.lineItems =[] 。谢谢!
    猜你喜欢
    • 2012-12-06
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-12-22
    • 1970-01-01
    • 2015-08-18
    • 2016-11-11
    相关资源
    最近更新 更多