Tuesday, June 4, 2024
 Popular · Latest · Hot · Upcoming
187
rated 0 times [  192] [ 5]  / answers: 1 / hits: 6852  / 11 Years ago, sun, february 9, 2014, 12:00:00

I've created an Angular directive that is supposed to close a modal when the escape key is pressed. 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. 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 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,
};

});

More From » angularjs

 Answers
1

Since classic events like click, keydown, etc are not managed by Angular but by the browser. If you modify your $scope inside of one of those events, you need to tell Angular that something have happened outside is context. That is the $apply. With $apply you can run things outside Angular context and make Angular aware when needed.


[#47905] Saturday, February 8, 2014, 11 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
alexandreah

Total Points: 720
Total Questions: 85
Total Answers: 90

Location: Central African Republic
Member since Fri, Jun 5, 2020
4 Years ago
alexandreah questions
Mon, Aug 9, 21, 00:00, 3 Years ago
Wed, Jan 8, 20, 00:00, 5 Years ago
Mon, Dec 16, 19, 00:00, 5 Years ago
Fri, Sep 27, 19, 00:00, 5 Years ago
;