Angular and Mousetrap - Isolate Scope
Example of wrapping Mousetrap in a directive
HTML
<script src="http://code.angularjs.org/1.0.3/angular.min.js"></script>
<div ng-app="keyExample">
<div ng-controller="RootController">
<keybinding on="g i" invoke="gotoInbox()" />
<div ng-controller="ChildController">
<keybinding on="g l" invoke="gotoLabel('Sent')" />
</div>
</div>
<div>Click in here to gain focus and then try the following key strokes</div>
<ul>
<li>"g i" to show a "Goto Inbox" alert</li>
<li>"g l" to show a "Goto Label" alert</li>
</ul>
</div>
JavaScript
var app = angular.module('keyExample', []);
app.directive('keybinding', function () {
return {
restrict: 'E',
scope: {
invoke: '&'
},
link: function (scope, el, attr) {
Mousetrap.bind(attr.on, scope.invoke);
}
};
});
app.controller('RootController', function ($scope) {
$scope.gotoInbox = function () {
alert('Goto Inbox');
};
});
app.controller('ChildController', function ($scope) {
$scope.gotoLabel = function (label) {
alert('Goto Label: ' + label);
};
});
/* mousetrap v1.3.2 craig.is/killing/mice */ (function () {
function s(a, b, c) {
a.addEventListener ? a.addEventListener(b, c, !1) : a.attachEvent("on" + b, c)
}
function y(a) {
if ("keypress" == a.type) {
var b = String.fromCharCode(a.which);
a.shiftKey || (b = b.toLowerCase());
return b
}
return h[a.which] ? h[a.which] : z[a.which] ? z[a.which] : String.fromCharCode(a.which).toLowerCase()
}
function t(a, b) {
a = a || {};
var c = !1,
d;
for (d in m) a[d] && m[d] > b ? c = !0 : m[d] = 0;
c || (p = !1)
}
function A(a, b, c, d, g) {
var f, e, h = [],
j = c.type;
if (!l[a]) return [];
"keyup" == j && u(a) && (b = [a]);
for (f = 0; f < l[a].length; ++f) if (e = l[a][f], !(e.seq && m[e.seq] != e.level) && j == e.action && ("keypress" == j && !c.metaKey && !c.ctrlKey || b.sort().join(",") === e.modifiers.sort().join(","))) d && e.combo == g && l[a].splice(f, 1), h.push(e);
return h
}
function v(a, b, c) {
if (!k.stopCallback(b, b.target || b.srcElement, c) && !1 === a(b, c)) b.preventDefault && b.preventDefault(), b.stopPropagation && b.stopPropagation(), b.returnValue = !1, b.cancelBubble = !0
}
function w(a) {
"number" !== typeof a.which && (a.which = a.keyCode);
var b = y(a);
...