[英]Angular controller scope not updating after jQuery ajax call
我有這個代碼,我無法看到問題的根源在哪里,我沒有在我的控制器的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
和label2
在div loadingthings中正確加載;
控制台中的newMsgs按其應有的方式進行解析;
我有它在其他頁面工作,但似乎我錯過了這個上的東西。我有<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>
當我執行此操作時,我在控制台中得到'undefined': angular.element($0).scope()
忽略我在評論中指出的其他架構問題,真正的問題是你使用jQuery
的ajax
而不是Angular的$http
。 當你不通過Angular做這樣的事情時,你在Angular的范圍之外工作,並且它不知道變化。 雖然不理想,但您可以使用$scope.$apply
讓角度知道某些內容在其知識之外更新。 這看起來像這樣:
$scope.$apply(function() {
$scope.msgs = newMsgs;
});
這告訴Angular你從一個它不知道的上下文(在這種情況下是jQuery ajax調用)中修改了它需要知道的東西。
有一些有效的使用$scope.$apply()
,例如在事件處理程序中,但大多數情況下它是不良做法的標志。 你絕對應該使用Angular的$http
進行ajax調用。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.