jQuery的AJAX调用后角控制器范围不更新 [英] Angular controller scope not updating after jQuery ajax call
问题描述
我有这个code和我看不出哪里是问题的根源,我不铬控制台收到任何错误
我的控制器:
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 :
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();
}
卷标1
和 LABEL2
是一个div里面loadedthings正确装入;
label1
and label2
are loaded correctly inside a div loadedthings;
在控制台newMsgs解析只是它应该的方式;
newMsgs in the console is parsed just the way it should;
我曾经有过打工的页面,但我好像错过了这个one.i东西有< HTML NG-应用>
标签:
i had it working for other pages but it seems that i missed something on this one.i have <html ng-app>
tag :
<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>
我得到控制台未定义当我执行这样的: angular.element($ 0).scope()
推荐答案
不顾我在评论中指出的其他结构问题,真正的问题是,你正在使用的jQuery
的 AJAX
而不是角的 $ HTTP
。当你不通过角做这样的事情,你的工作角的范围之外,它不知道的变化。虽然不理想,您可以使用 $范围。$适用
让角知道的东西是它的知识以外更新。这将是这样的:
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:
$scope.$apply(function() {
$scope.msgs = newMsgs;
});
这是告诉角度,你已经修改它的东西需要了解从上下文,它不知道(在这种情况下,jQuery的AJAX调用)。
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).
有中 $范围一些有效的使用。$适用()
,比如在事件处理程序,但大多数其他时间的不良做法的迹象。你绝对应该采用了棱角分明的 $ HTTP
的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.
这篇关于jQuery的AJAX调用后角控制器范围不更新的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!