更改$ document.on('点击')未反映在视图中

时间:2016-08-17 06:42:23

标签: angularjs angularjs-directive javascript-events angularjs-scope

我有一个角度指令ngx-notifications,它位于控制器MenuBarController内。

查看

<div class="row" ng-controller="MenuBarController">
 ...
  <span ng-click="ShowNotifications()">click me</span>
  <div ng-show="NotificationsVisible" ngx-notifications="NotificationsVisible">

控制器

$scope.NotificationsVisible = false;

function ShowNotifications(){
  $scope.NotificationsVisible = !$scope.NotificationsVisible;
}


setInterval(function(){
  console.log($scope.NotificationsVisible);
},1000);

指令

angular.module('app').directive('ngxNotifications', NotificationsDirective);

NotificationsDirective.$inject = ['$document'];
function NotificationsDirective($document) {

  return {
    restrict: "A",
    scope: false,
    link: function ($scope, $elem, $attr) {
      var key = $attr.ngxNotifications;

      $document.on("click",function ($e) {
        if(!$elem[0].contains($e.target)){
          console.log($scope,key); // logs correct scope and key
          //neither of the two following lines are reflected in the view
          $scope[key] = false;
          $scope.NotificationsVisible = false;

        }
      });

    }
  }
}

span[ng-click]切换了我的通知框的可见性,但出于某种原因,当我的directive通过$document.on('click')进行更改时,角度并没有获得更改,尽管事实如此我setTimeout中的controller表示值已更改。这是为什么?

我无法在我的控制器和指令之间创建一个单独的范围,我只需要添加这些额外的功能。

1 个答案:

答案 0 :(得分:0)

正如我所怀疑的,由于某种原因,$document::on方法不是角度摘要的一部分,添加$scope.$apply有效,但这并没有真正有意义(我从未离开过角度代码改变模型):

$document.bind("click",function ($e) {
  if($scope[key] && !$elem[0].contains($e.target)){
    $scope.$apply(function () {
      $scope[key] = false;
    });
  }
});