Created
August 1, 2015 18:35
-
-
Save zbicin/2b3fdf538936287c1a96 to your computer and use it in GitHub Desktop.
Directive focusing an element when given scope variable becomes boolean true.
This file contains hidden or 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
| /* | |
| * Directive focusing an element when given scope variable becomes boolean true. | |
| * If the variable becomes equal to boolean false the element is blurred. | |
| * Usage: <input type="text" focus-on="someScopeVariable === 1" /> | |
| */ | |
| angular.module('FocusOnDirective').directive('focusOn', ['$timeout', function ($timeout) { | |
| 'use strict'; | |
| return { | |
| restrict: 'A', | |
| scope: { | |
| focusOn: '=' | |
| }, | |
| link: function (scope, element) { | |
| scope.$watch('focusOn', function (newValue, oldValue) { | |
| if (newValue !== oldValue) { | |
| if (newValue === true) { | |
| $timeout(function () { | |
| element[0].focus(); | |
| }, 0); | |
| } else if (newValue === false) { | |
| $timeout(function () { | |
| element[0].blur(); | |
| }, 0); | |
| } | |
| } | |
| }); | |
| } | |
| }; | |
| }]); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment