I have a custom icon component using isolate scope where a user can define what he or she wants to happen on ng-click:
<ers-icon name="history" ng-click="ctrl.clickAlert('history')"></ers-icon>
This calls a method from within the user's controller as follows:
this.clickAlert = function (icon) {
alert("You selected the " + icon + " icon.");
}
I need to add enter key functionality to the icon component without adding any other code, from I have above, to my html element. So essentially listen for the enter key press from within the directive and evaluate the ng-click directive on ers-icon. Here is what I have as the icon directive:
// on click works fine
.on("click", (event:JQueryEventObject):void => {
if (this.ngDisabled) {
event.preventDefault();
event.stopPropagation();
}
});
}
//execute whatever function is specified inside ng-click on enter key press
.on("keydown", (event:JQueryEventObject):void => {
if (event.keyCode === 13) {
if (this.ngDisabled) {
event.preventDefault();
event.stopPropagation();
} else {
// need to execute ng-click here
// this try doesn't work, gives me undefined
$scope.$apply(() => {
$scope.$eval($attr.ngClick);
}
}
}
});
This runs fine on enter key press but I can't get the controller function defined on ng-click to run.
I thought maybe $eval or $parse would work but it looks like those will only evaluate expressions within {{}}. What is the best way to execute that ng-click attribute so that when a user hits the enter key, the "this.clickAlert" function is ran and an alert is shown on the screen?
I can't really change any of the code as is above, just looking for the solution within the else statement of the on keydown listener.
I solved it this way:
.on("keydown", (event:JQueryEventObject):void => {
if (event.keyCode === 13) {
if (this.ngDisabled) {
event.preventDefault();
event.stopPropagation();
} else {
// need to execute ng-click here
this.element.trigger("click");
}
}
});