Skip to content

Instantly share code, notes, and snippets.

@onjiro
Created July 27, 2014 08:20
Show Gist options
  • Save onjiro/0295ac5a1f51da101806 to your computer and use it in GitHub Desktop.
Save onjiro/0295ac5a1f51da101806 to your computer and use it in GitHub Desktop.
入力フォームに変更があったらフォーカスする directive
angular.module('ngFocusOnChange', [])
.directive('ngFocusOnChange', ['$timeout', function($timeout) {
return {
link: function(scope, element, attrs) {
scope.$watch(attrs.ngFocusOnChange, function(newValue, oldValue) {
// 以下のエラーを避けるために $timeout を使用
// watch の最中に DOM イベントを発生させてはいけない
// "Error: [$rootScope: inprog]"
// https://docs.angularjs.org/error/$rootScope/inprog?p0=$digest
if (newValue !== oldValue) {
$timeout(function() { element.focus(); });
}
});
}
};
}]);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment