简体   繁体   English

使用转义键关闭模态的Angular指令

[英]Angular directive to close a modal with the escape key

I've created an Angular directive that is supposed to close a modal when the escape key is pressed. 我创建了一个Angular指令,该指令应该在按下转义键时关闭一个模态。 The modal service works just fine when used within controllers, but for some reason it doesn't work within this directive. 模态服务在控制器中使用时工作正常,但由于某种原因,它在该指令中不起作用。 The following code will print hello when escape is pressed but it will not hide the modal. 按下escape时,以下代码将打印hello ,但不会隐藏模态。 Any ideas? 有任何想法吗?

DIRECTIVE 指示

app.directive("dpEscape", function(modal) {
  return function(scope, element, attributes) {
    element.on("keyup", function(event) {
      if (event.keyCode == 27) {
        console.log("hello");
        modal.hide();
      }
    });
  };
});

I don't actually think any of the following code is relevant to the problem, but I could be wrong. 我实际上并不认为以下任何代码与问题相关,但我可能是错的。 Since I know people are going to ask for it anyways, here it is: 因为我知道人们无论如何都要求它,这里是:

HTML HTML

...
<html ng-app="trread" ng-controller="Main" dp-escape>
...

SERVICE 服务

app.factory("modal", function() {

  var urlPath = "/templates/modals/";
  var visible = false;
  var templateUrl = "";
  var content = {};
  var controller = {};
  var size = {width: 500, height: 500};

  var show = function() {
    visible = true;
  }

  var hide = function() {
    visible = false;
  }

  var setTemplate = function(url) {
    templateUrl = urlPath + url + ".html";
  }

  var getTemplate = function() {
    return templateUrl;
  }

  var setContent = function(contentObj) {
    content = contentObj;
  }

  var getContent = function() {
    return content;
  }

  var setController = function(controllerObj) {
    controller = controllerObj;
  }

  var getController = function() {
    return controller;
  }

  var isVisible = function() {
    return visible;
  }

  return {
    show: show,
    hide: hide,
    setTemplate: setTemplate,
    getTemplate: getTemplate,
    setContent: setContent,
    getContent: getContent,
    setController: setController,
    getController: getController,
    isVisible: isVisible,
  };

});

Since classic events like click , keydown , etc are not managed by Angular but by the browser. 由于clickkeydown等经典事件不是由Angular管理,而是由浏览器管理。 If you modify your $scope inside of one of those events, you need to tell Angular that something have happened outside is context. 如果在其中一个事件中修改$scope ,则需要告诉Angular外部发生的事情是上下文。 That is the $apply . 这是$apply With $apply you can run things outside Angular context and make Angular aware when needed. 使用$apply您可以在Angular context之外运行,并在需要时使Angular知道。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM