Created
August 21, 2012 22:15
-
-
Save nobuf/3419910 to your computer and use it in GitHub Desktop.
Supporting placeholder on IE9 with AngularJS + jQuery
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
angular.module('test', []) | |
.directive('placeholder', function($timeout){ | |
if (!$.browser.msie || $.browser.version >= 10) { | |
return {}; | |
} | |
return { | |
link: function(scope, elm, attrs){ | |
if (attrs.type === 'password') { | |
return; | |
} | |
$timeout(function(){ | |
elm.val(attrs.placeholder).focus(function(){ | |
if ($(this).val() == $(this).attr('placeholder')) { | |
$(this).val(''); | |
} | |
}).blur(function(){ | |
if ($(this).val() == '') { | |
$(this).val($(this).attr('placeholder')); | |
} | |
}); | |
}); | |
} | |
} | |
}); |
Why do you use a $timeout?
I think using jQuery isn't sometimes useful. You can use this instance:
$timeout(function(){
elm.val(attrs.placeholder);
elm.bind('focus', function(){
if( elm.value === scope.$eval(attrs.placeholder)) {
elm.value = '';
}
});
elm.bind('blur', function(){
if( elm.value === '' ) {
elm.value = scope.$eval(attrs.placeholder);
}
});
});
You can also use the following angular.js module which adds the "placeholder" functionality for older browsers (IE9 included):
you should consider using this statement for placeholder detection rather than browser sniffing. if ('placeholder' in $('<input type="text">')[0] == false)
Also you gist will leak memonry as you are not cleaning up the events
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Thanks!