0

I'm running into an unusual behaviour with ng-switch that I'm not able to figure out. At the top of my page, I have

#content{"ng-switch" => "root.showAlert"}
  %div.alert.ng-cloak#alert{"ng-switch-when" => "true"}
    {{root.alert.message}}
    %div.close
      %a{:href => "#", "ng-click" => "dismissAlert()"}
        =image_tag "icons/icon-close-black.png"

In one of my controllers (highest level) I have the following action

$scope.displayAlert = function(message) {
  $scope.root.alert = {
    message: message
  };
  $scope.root.showAlert = true;

  if (!$scope.$$phase) {
    $rootScope.$digest();
  }
}

$scope.root is defined in the $rootScope so is accessible to everything.

When I change the root.showAlert flag to true, I am expecting to see the alert appear as it should be watching this variable, however it isn't happening immediately, and instead showing when I change something else in the app by performing any other action.

By adding my $rootScope.$digest() it works and displays immediately, but I was wondering why it won't do it on its own?

Dismissing:

$rootScope.dismissAlert = function() {
  $scope.root.showAlert = false;
  delete $scope.root.alert;
}
4

1 回答 1

2

如果调用 会digest()导致 UI 中的某些内容发生变化,否则,这意味着影响该 UI 的数据正在一些异步代码或其他一些不是从 AngularJS 自己的上下文中执行的代码中发生变化。

在 Angular 的内置功能(ng-click$http回调等)中发生的所有主要操作都会在相关范围内调用scope.$apply(反过来调用scope.$digest)以在整个系统中传播更改。如果您要从 Angular 的“世界”之外更改代码,则需要将功能包装在 a scope.$apply(或 call scope.$digest)中以自己进行。

在这种情况下,Angular 可能正在附加按钮的范围上运行摘要,但是由于您要在范围上更改数据,因此您需要自己启动摘要。

有关更多信息,请参阅AngularJS 中的数据绑定中的此答案。

于 2013-05-24T15:00:35.393 回答