Skip to content

Instantly share code, notes, and snippets.

@nobuf
Created August 21, 2012 22:15
Show Gist options
  • Star 7 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save nobuf/3419910 to your computer and use it in GitHub Desktop.
Save nobuf/3419910 to your computer and use it in GitHub Desktop.
Supporting placeholder on IE9 with AngularJS + jQuery
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'));
}
});
});
}
}
});
@scottweinert
Copy link

Thanks!

@zhenghao1
Copy link

Why do you use a $timeout?

@myfoxtail
Copy link

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);
}
});
});

@urish
Copy link

urish commented Jul 3, 2013

You can also use the following angular.js module which adds the "placeholder" functionality for older browsers (IE9 included):

https://github.com/urish/angular-placeholder-shim

@blowsie
Copy link

blowsie commented Nov 4, 2013

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