/
todoKbd.js
46 lines (42 loc) · 1.09 KB
/
todoKbd.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
/*global angular */
/**
* Directive that implements the keyboard functionality for the entire todo application
*/
angular.module('todomvc').directive('todoKbd', function () {
'use strict'
var ESCAPE_KEY = 27
var TAB_KEY = 9
var DELETE_KEY = 46
const ENTER_KEY = 13
return {
restrict: 'A',
scope: true,
link: function (scope, elem, attrs) {
elem
.on('keydown', function (event) {
if (event.keyCode === ENTER_KEY) {
scope.editTodo(scope.todo)
scope.$apply()
return
}
var focus = false
if (!scope.editedTodo && event.keyCode !== DELETE_KEY) {
return
}
if (event.keyCode === ESCAPE_KEY) {
scope.revertEdits(scope.todo)
focus = true
} else if (event.keyCode === DELETE_KEY) {
scope.removeTodo(scope.todo)
}
scope.$apply()
if (focus) {
elem[0].querySelector('a').focus()
}
})
.on('$destroy', function () {
elem.off('keydown')
})
},
}
})