Angular.js ng show and directive没有'不起作用

Angular.js ng-show and directive doesn't work

本文关键字:不起作用 没有 directive js ng show and Angular      更新时间:2023-09-26

我有以下html:

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

Angular.js应用程序:

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发生了更改。问题出在哪里?

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

您正在创建一个事件侦听器,该侦听器在角度摘要循环之外执行。因此,您必须告诉angular开始一个新的摘要周期,以便获取更改。您可以使用scope$申请这样做:

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

演示

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