javascript jQuery ajax 调用后,Angular 控制器范围未更新
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/21127709/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Angular controller scope not updating after jQuery ajax call
提问by zerzer
i have this code and i can't see where is the source of problem, i don't get any error in the chrome console my controller :
我有这个代码,但我看不到问题的根源在哪里,我的控制器在 chrome 控制台中没有收到任何错误:
function notifController($scope) {
$scope.refreshMsgs = function () {
$.post("notification-center-trait.aspx")
.success(function (data) {
$("#loadedthings").html(data);
newMsgs = JSON.parse($("#label1").html());
$scope.msgs = newMsgs;
});
}
$scope.refreshMsgs();
}
label1
and label2
are loaded correctly inside a div loadedthings;
label1
并label2
在 div 加载的东西中正确加载;
newMsgs in the console is parsed just the way it should;
控制台中的 newMsgs 被解析为它应该的方式;
i had it working for other pages but it seems that i missed something on this one.i have <html ng-app>
tag :
我让它在其他页面上工作,但似乎我在这个页面上遗漏了一些东西。我有<html ng-app>
标签:
<div ng-controller="notifController">
<div class="row">
{{msgs.length}} new msgs :
<table class="table">
<tbody >
<tr ng-repeat="msg in msgs">
<td>
{{msg.sender}}
</td>
<td>
{{msg.message}}
</td>
<td>
{{msg.date}}
</td>
</tr>
</tbody>
</table>
</div>
</div>
i get 'undefined' in the console when i execute this : angular.element($0).scope()
当我执行这个时,我在控制台中得到“未定义”: angular.element($0).scope()
回答by m59
Disregarding other architectural issues I pointed out in the comments, the real issue is that you're using jQuery
's ajax
instead of Angular's $http
. When you don't do things like that through Angular, you're working outside of Angular's scope and it doesn't know about changes. While not ideal, you can use $scope.$apply
to let angular know something was updated outside of its knowledge. That would look like this:
不考虑我在评论中指出的其他架构问题,真正的问题是您使用jQuery
的是'sajax
而不是 Angular 的$http
. 当你不通过 Angular 做这样的事情时,你是在 Angular 的范围之外工作,它不知道变化。虽然不理想,但您可以使用$scope.$apply
让 angular 知道某些内容在其知识范围之外进行了更新。看起来像这样:
$scope.$apply(function() {
$scope.msgs = newMsgs;
});
That is telling Angular that you've modified something it needs to know about from a context that it doesn't know about (the jQuery ajax call in this case).
这告诉 Angular,您已经修改了它需要从它不知道的上下文(在本例中为 jQuery ajax 调用)中了解的内容。
There are some valid uses of $scope.$apply()
, such as in event handlers, but most other times it is a sign of bad practices. You should definitely be using Angular's $http
for ajax calls.
有一些有效的用途$scope.$apply()
,例如在事件处理程序中,但大多数情况下它是不良做法的标志。您绝对应该将 Angular$http
用于 ajax 调用。