0

我有角度摘要循环的问题。当我进行 http 调用并将响应放入 $scope 时,该 var 在下一个摘要循环之前不会在视图中更新。

例如,我将以下调用包装到视图上的函数和按钮中,该视图使用 ng-click 调用函数。第一次单击按钮时,视图上什么也没发生(发送了 http 响应并收到了响应)。第二次单击按钮后,视图将使用先前响应的数据更新,当前响应在下次单击后更新等...

$scope.loadItems = function(){
   ItemService.getData().then(function(rsp) {
      $scope.items = rsp.data;
    });
}

ItemService.getData() 基本上是包装 $http 调用:

getData : function(){
    return $http({
    method: 'GET',
    url: '/api/items'
    });
}

和 html

<button ng-click="loadItems()">Load</button>

谢谢!

4

2 回答 2

1

好的,我想问题如下。我打赌你会在 ng-repeat 中使用 $scope.items,对吗?例如

<ul>
    <li ng-repeat="item in items">
        //Here goes my little item
    </li>
</ul>

正确的?嗯,有一个问题。ng-repeat 引用“items”集合,一旦引用的集合发生更改,HTML 就会更新。但是...做的问题

$scope.items = rsp.data;

是您为“项目”分配了一个未被 ng-repeat 引用的全新集合 - 它仍然引用未更改的旧集合。因此以下应该有效 - 在您的 $scope 中使用一个点。

控制器:

$scope.data = {};

ItemService.getData().then(function(rsp) {
    $scope.data.items = rsp.data;
});

看法:

<ul>
    <li ng-repeat="item in data.items">
        //Here goes my little item
    </li>
</ul>

换句话说,问题不在于调用摘要循环——它被调用了。问题在于滥用 $scope。

这个链接应该很有帮助。它更详细地解释了范围的细微差别。

于 2016-02-10T14:51:14.203 回答
-1

您需要将 getData() 更改为如下所示:

getData: function() {
  return $http({
  method: 'GET',
  url: '/api/items'
  }).then(function(response) {
    return response.data;
  }, function(error) {
    return error;
  });
}

和 $scope.loadItems() 到

$scope.loadItems = function(){
   ItemService.getData().then(function(rsp) {
      $scope.items = rsp;
    });
}
于 2016-02-10T15:12:07.670 回答