【问题标题】:AngularJS + $resource + ng-repeatAngularJS + $resource + ng-repeat
【发布时间】:2014-08-11 04:23:04
【问题描述】:

我在执行以下顺序的一个步骤时遇到问题:

  1. 将数据发布到休息服务器并获得完整的记录作为回报。
  2. 用新记录更新网页。

我有一个可用的 $resource 并使用以下命令在控制器中发布我的帖子。

$scope.update = function(newRecord) {
    //use resource called apiClient to POST a record to API server
    apiClient.save(newRecord).$promise.then(function(response) {           
         //attempt to add new complete record to list on the web page
         $scope.existingRecords.push(response.data);
    });
};

但是我的 ng-repeat 列表不会更新以反映新条目。我可以确认数组 $scope.existingRecords(它驱动我的 ng-repeat)正在获取新记录,但在 DOM 中没有任何乐趣。

我听说过一些选择,但我没有运气......

$scope.update = function(newRecord) {
    //use resource called apiClient to POST a record to API server
    apiClient.save(newRecord).$promise.then(function(response) {           
         //attempt to add new complete record to list on the web page
         $scope.existingRecords.push(response.data);
         //let's try to force an update
         $scope.$apply();
    });
};

给我一​​个错误....

错误:[$rootScope:inprog] $digest 已经在进行中

修改以绕过摘要错误...

....
$timeout(function() {
    $scope.$apply();
});
....

运行无错误,但也不更新 ng-repeat。

更新 新创建的记录添加:

$scope.existingRecords.push(response.data);

Firebug 显示已有记录和新记录的方式略有不同:

Resource { id="2", name="existing-record", more...}


Object { id="41", name="just posted via ajax", more...}

不确定这是否重要,也许我以错误的方式将新记录添加到模型中?

【问题讨论】:

  • 你找到解决方案了吗?
  • 恐怕我没有。不久之后,我放弃了 Angular,喝了 Ember kool-aid。
  • LOl。好,谢谢。我的直接问题似乎是缓存刷新问题。 ng-repeat 在彻底清除浏览器和服务器缓存后正确呈现。

标签: angularjs angularjs-ng-repeat angularjs-resource


【解决方案1】:

您提到您已经尝试过$scope.apply(),但应该是$scope.$apply(); 在推送response.data 后调用它应该确保您的视图已更新。

【讨论】:

  • 我的错,这是一个错字,我将在 OP 中更正。
【解决方案2】:

当使用$resource api 调用的$promise 时,结果将直接传递给then() 函数。

因此,您必须将 response.data 更改为 data,如下所示:

$scope.update = function(newRecord) {
    // use resource called apiClient to POST a record to API server
    apiClient.save(newRecord).$promise.then(function(data) {           
        //attempt to add new complete record to list on the web page
        $scope.existingRecords.push(data);
    });
};

希望这会有所帮助。

【讨论】:

  • 我从我的 api 得到的响应格式如下... {"status":"OK","data":code{"id":"39","name" :"test","imageUrl":null,"sn-p":"droid","age":1}} 我将完整的响应对象放入 $promise.then。所以我只将 response.data 部分添加到我的模型中。新模型记录已正确添加,只是不会更新 ng-repeat。
  • existingRecords 列表中是否有重复项?
  • 没有重复,但我看到新添加的记录看起来略有不同。 Firebug 将现有记录的记录显示为Resource { id="2", name="MOTOROLA XOOM\u2122", snippet="The Next, Next Generatio...ndroid 3.0 (Honeycomb).", more...},但我的新记录是....Object { id="41", name="asdf asdf asdf", snippet="droid", more...}
  • 请在问题中包含上述详细信息,在评论中很难看到。
  • 我讨厌评论系统:)
猜你喜欢
  • 1970-01-01
  • 2017-12-22
  • 2016-08-02
  • 1970-01-01
  • 2013-11-23
  • 1970-01-01
  • 2017-11-19
  • 2014-09-07
  • 1970-01-01
相关资源
最近更新 更多