一尘不染

jQuery ajax调用后,Angular控制器范围未更新

angularjs

我有这段代码,我看不出问题的根源在哪里,我在控制器的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();
}

label1label2正确加载到div加载的东西中;

控制台中的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>

执行此命令时,我在控制台中得到“未定义”: angular.element($0).scope()


阅读 246

收藏
2020-07-04

共1个答案

一尘不染

忽略我在评论中指出的其他体系结构问题,真正的问题是您使用jQuery的是ajax而不是Angular的$http。当您不通过Angular做类似的事情时,您就在Angular的范围之外工作,并且它不知道更改。虽然不理想,但您可以$scope.$apply用来让angular知道某些超出其知识范围的更新。看起来像这样:

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

这告诉Angular,您已经修改了它需要从其不了解的上下文中了解的某些信息(在本例中为jQuery ajax调用)。

有一些有效的用法$scope.$apply(),例如在事件处理程序中,但是在大多数情况下,这是不良做法的标志。您绝对应该使用Angular
$http进行ajax调用。

2020-07-04