我在AngularJS中使用了一个控制器,如下所示(根据thinkster.io上的angularjs教程的第3章: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)
给出正确的输出(删除帖子)。
但DOM没有得到更新(帖子仍然显示)。 如果我在Chrome浏览器中查看AngularJS调试器的范围,我删除的帖子仍然存在。 我必须刷新才能在DOM中查看删除后的内容。 $scope.$apply()
似乎没有工作。
我花了很多时间,并认为这与$ scope变量的作用域有关。所以我来到以下解决方案: 我将window.obj设置为等于$ scope,然后在deletePost函数中使用window.obj而不是范围。
像这样:
window.obj = $scope;
$scope.deletePost = function (postId) {
Post.delete({ id: postId },function() {
delete window.obj.posts[postId];
});
};
它现在。 任何人都可以解释为什么我必须为此设置一个全局变量? 我是否犯了某种错误?
感谢
这不就是回调中的'delete $ scope.posts [postId];'的作用吗? (帖子是一个json对象,而不是数组)当我在回调中的console.log($ scope.posts)时,我可以看到帖子DID被删除。但不知何故,这并不反映在DOM – jitin 2014-09-05 13:39:49
然后我无法弄清楚问题在哪里。我试图重现您的问题,但它看起来像预期的那样工作:http://plnkr.co/edit/x0rS3I2HSWh49ieGCV2P?p=preview。 – 2014-09-05 15:03:18
发现错误:我不必要地将ngSanitize作为模块的依赖项。当我删除它时,该应用程序开始工作。在进一步的检查中,我的angular-sanitize.js文件不完整。现在替换文件和一切正常 - 即使有ngSanitize依赖关系。谢谢 :) – jitin 2014-09-05 16:15:48