Angular.js ng-show和指令不起作用

时间:2016-07-24 18:47:23

标签: javascript angularjs

我有以下html:

<div class="modal-dialog" ng-controller="modal-ctrl" ng-show="showModal" execute-on-esc>

Angular.js app:

app.controller('modal-ctrl', function($scope) {
    $scope.showModal = true;
});

app.directive('executeOnEsc', function ($document) {
    return {
        restrict: 'A',
        link: function (scope) {
            return $document.bind('keydown', function(event) {
                event.which === 27? scope.showModal = false : false;
            });
        }
    }
});

一切正常,$ scope.showModal变为false,但ng-show并未对此更改做出响应。为什么? Console.log显示$ scope.showModal更改。 问题出在哪里?

1 个答案:

答案 0 :(得分:1)

return $document.bind('keydown', function(event) {
    event.which === 27? scope.showModal = false : 
});

您正在创建一个事件侦听器,此侦听器在角度摘要周期之外执行。因此,您必须告诉angular开始一个新的摘要周期,以便获取更改。您可以使用scope.$apply执行此操作:

return $document.bind('keydown', function(event) {
    scope.$apply(function(){
        event.which === 27? scope.showModal = false : 
    });
});

演示

&#13;
&#13;
var app = angular.module("app", []);

app.controller('modal-ctrl', function($scope) {
  $scope.showModal = true;
});

app.directive('executeOnEsc', function($document) {
  return {
    restrict: 'A',
    link: function(scope) {
      return $document.bind('keydown', function(event) {
        scope.$apply(function() {
          event.which === 27 ? scope.showModal = false : false;
        });
      });
    }
  }
});
&#13;
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<div ng-app="app">
  <div class="modal-dialog" ng-controller="modal-ctrl" ng-show="showModal" execute-on-esc>
    My Modal
  </div>
</div>
&#13;
&#13;
&#13;