Angular控制器作用域在jQuery ajax调用之后未更新

9 浏览
0 Comments

Angular控制器作用域在jQuery ajax调用之后未更新

我有这段代码,但我看不到问题的来源,控制台中不会出现任何错误

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();
}

label1label2被正确加载到一个名为loadedthings的div中;

控制台中的newMsgs被正确解析;

我在其他页面上让它工作了,但在这个页面上好像我错过了什么。我有一个标记:

 
    {{msgs.length}} new msgs :

 

{{msg.sender}} {{msg.message}} {{msg.date}}

 

当我执行angular.element($0).scope()时,在控制台中我得到\'undefined\'

admin 更改状态以发布 2023年5月21日
0
0 Comments

忽略我在评论中指出的其他架构问题,真正的问题是你使用了 jQuery 的 ajax 而不是 Angular 的 $http 。当你不通过 Angular 使用这些方法时,你就在 Angular 的范围之外工作,它不知道这些变化。虽然不是理想的方法,但是你可以使用 $scope.$apply 来告诉 angular 有些东西被修改了,而它不知道这些。示例代码如下:

$scope.$apply(function() {
  $scope.msgs = newMsgs;
});

这告诉 Angular 你已经从它不知道的上下文中修改了它需要知道的东西(在这个例子中是 jQuery 的 ajax 调用)。

虽然在事件处理程序中使用 $scope.$apply() 是有些合理的,但大多数情况下,这是不好的做法。您应该一定使用 Angular 的 $http 来进行 ajax 调用。

0