3

이스케이프 키를 누를 때 모달을 닫아야하는 각도 지시문을 만들었습니다. 모달 서비스는 컨트롤러 내에서 사용하면 잘 작동하지만, 어떤 이유로이 지시어 내에서 작동하지 않습니다. 다음 코드는 이탈을 누르면 hello을 인쇄하지만 모달을 숨기지는 않습니다. 어떤 아이디어?이스케이프 키를 사용하여 모달을 닫는 각도 지시문

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

실제로 다음과 같은 코드의 문제와 관련이 있다고 생각하지 않지만, 내가 잘못 될 수 있습니다. 나는 사람들이 어쨌든 그것을 물어가는 알고 있기 때문에, 여기있다 :있는 등 click 같은 고전 이벤트, keydown, 이후

HTML

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

서비스

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

}); 
+0

이 코드를 읽지는 못하지만, if (지시어에 따라)를'scope '에 감싸려고하십시오. $ apply()' –

+0

고마워요! 그게 효과가 있었어. –

+0

좋아, 그럼 내가 적절한 응답을 추가했습니다. –

답변

5

Angular이 아니라 브라우저가 관리합니다. 해당 이벤트 중 하나의 내부에서 $scope을 수정하면 Angular에게 외부에서 발생한 일이 문맥이라고 말해야합니다. 그것이 $apply입니다. $apply을 사용하면 Angular context 외부로 실행하고 필요시 Angular을 인식 할 수 있습니다.

관련 문제