Last active
August 29, 2015 13:56
-
-
Save jchadwick/9236562 to your computer and use it in GitHub Desktop.
AngularJS Inline Editor (TypesSript)
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/// <reference path="../../scripts/typings/angularjs/angular.d.ts" /> | |
/// <reference path="../../Scripts/typings/angularjs/angular-scenario.d.ts" /> | |
module InlineEditor { | |
'use strict'; | |
function InlineEditor(): ng.IDirective { | |
function link(scope: ng.IScope, container: ng.IAugmentedJQuery, attrs: ng.IAttributes, ngModel: ng.INgModelController) | |
: void { | |
var editor = container.find('.editor'), | |
editTarget = container.find('.edit-target'); | |
ngModel.$render = function () { | |
editor.val(ngModel.$viewValue || ''); | |
editTarget.html(ngModel.$viewValue || ''); | |
}; | |
editTarget.on('click', function () { | |
enableEditing(); | |
}); | |
editor | |
.on('blur', function () { | |
save(); | |
}) | |
.on('keydown', function (evt) { | |
switch (evt.keyCode) { | |
// Enter to save | |
case 13: | |
// Trigger blur event to save, as wired above | |
// NOTE: if we saved here, the save would get triggered | |
// again on blur, so just call blur directly. | |
editor.triggerHandler('blur'); | |
break; | |
// Esc to cancel | |
case 27: | |
reset(); | |
break; | |
default: | |
// Do nothing | |
break; | |
} | |
}); | |
function enableEditing(): void { | |
container.addClass('editing'); | |
editTarget.hide(); | |
editor.show(); | |
editor.focus(); | |
} | |
function reset(): void { | |
ngModel.$setPristine(); | |
ngModel.$render(); | |
editor.hide(); | |
editTarget.show(); | |
container.removeClass('editing invalid'); | |
} | |
function save(): void { | |
var updatedValue = editor.val(); | |
if (updatedValue != ngModel.$viewValue) { | |
scope.$apply(function () { | |
ngModel.$setViewValue(updatedValue); | |
}); | |
} | |
reset(); | |
} | |
} | |
return { | |
link: link, | |
priority: 100, | |
replace: true, | |
'require': 'ngModel', | |
restrict: 'AE', | |
scope: { | |
ngModel: '=' | |
}, | |
template: | |
'<span class="inline-editor">' + | |
' <span class="edit-target" />' + | |
' <input type="text" name="editor" class="editor" style="display:none;" />' + | |
'</span>' | |
}; | |
} | |
angular.module('InlineEditor', []) | |
.directive('inlineEditor', InlineEditor); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment