Angularjs-在$resource-delete方法的回调中更新$scope的问题(thinkster.io第三章

Angularjs- Issue with updating $scope in the callback of $resource delete method (thinkster.io 3rd chapter)

本文关键字:问题 io 第三章 scope thinkster resource-delete 方法 回调 Angularjs- 更新      更新时间:2023-09-26

我在AngularJS中使用的控制器如下(根据thinkster.io上AngularJS教程的第三章:http://www.thinkster.io/angularjs/S2MxGFCO0B/3-communicating-with-a-server-using-a-service-and-resource)

posts.js

app.controller('postCtrl', function ($scope, Post) {
  $scope.posts = Post.get();
  $scope.post = { url: 'http://', title: '' };
  $scope.submitPost = function () {
    ...
  };
  $scope.deletePost = function (postId) {
    Post.delete({ id: postId }, function () {
      delete $scope.posts[postId];
      console.log($scope.posts);
    });
  };
});

post.js

app.factory('Post', function ($resource) {
  return $resource('https://luminous-heat-3725.firebaseIO.com/posts/:id.json');
});

posts.html

<div ng-repeat="(postId,post) in posts">
  <a href="{{post.url}}">{{post.title}}</a>
  <a href="#" ng-click="deletePost(postId);">Delete</a>
</div>

这是一个简单的控制器,有一个提交帖子的功能和一个删除帖子的功能。

我面临的问题是deletePost函数中的回调似乎不起作用。因此,行delete $scope.posts[postId]一开始似乎是有效的,而console.log($scope.posts)给出了正确的输出(删除了post)。

但是DOM并没有得到更新(帖子仍然显示)。如果我查看Chrome中AngularJS调试器中的作用域,我删除的帖子仍然存在。我必须刷新才能在DOM中看到删除后的内容。$scope.$apply()似乎不起作用。

我花了很多时间,发现这与$scope变量的作用域有关。因此,我得出了以下解决方案:我将window.obj设置为等于$scope,然后在deletePost函数中使用window.obj而不是scope。

像这样:

window.obj = $scope;
$scope.deletePost = function (postId) {
  Post.delete({ id: postId },function () {
    delete window.obj.posts[postId];
  });
};

它现在起作用了。有人能解释为什么我必须为此设置一个全局变量吗?我是不是犯了某种错误?

感谢

Post.delete正在删除服务器中的资源,但这与当前模型($scope.posts)无关。如果您也想更新它,可以调用$scope.posts.splice(postId, 1)