Angularjs-在$resource-delete方法的回调中更新$scope的问题(thinkster.io第三章
Angularjs- Issue with updating $scope in the callback of $resource delete method (thinkster.io 3rd chapter)
我在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)
。
相关文章:
- 性能问题高图表图和 socket.io
- 'simple'套接字中的作用域问题.IO服务器
- Node.js/Socket.io适用于除Firefox之外的所有应用程序,这可能是缓存问题
- 关于socket.io实时文本显示的问题
- 问题-将angularjs与socket.io集成
- socket.io + Sencha 中的 JavaScript 命名空间问题
- 向所有具有 socket.io 的客户端发出问题
- 与socket.io相关的可伸缩性问题
- socket.io-使用命名空间时出现套接字变量问题
- socket.io聊天示例-表单提交问题
- Node Socket.io对象出现问题
- Angularjs-在$resource-delete方法的回调中更新$scope的问题(thinkster.io第三章
- Yammer JS SDK认证示例访问控制允许来源问题github.io
- TheIntern.IO测试运行程序实习生客户端问题“;试图要求卸载的模块superagent”
- Angular.js + Socket.iOS7 / Safari的io图像渲染问题
- webdriver.IO异步问题-点击一个元素,然后输入文本
- 插座有问题.IO和express
- Node JS Socket IO聊天问题
- 使用socket.io在Node.js上运行server.js文件有问题
- 烦人且奇怪的正则表达式问题:“io.”与“函数”一词匹配