Skip to content

Instantly share code, notes, and snippets.

@kiddpt
Last active October 26, 2015 12:40
Show Gist options
  • Save kiddpt/da5e24b7010c2454fa15 to your computer and use it in GitHub Desktop.
Save kiddpt/da5e24b7010c2454fa15 to your computer and use it in GitHub Desktop.
AngularJS placeholder support, no jQuery. Does not create a new input element to avoid losing ng-model binding issues.
(function() {
'use strict';
var n = 0;
angular.module('testApp')
.directive('placeholder', ['$timeout', '$document',
function($timeout, $document) {
var i = document.createElement('input');
if ('placeholder' in i) {
return {}
}
return {
restrict: 'EA',
link: function(scope, element, attrs) {
if (attrs.shimmed) return;
var id = attrs.placeholder.toLowerCase().replace(/ /g, '-') + n++;
var label = angular.element('<label style="font-size: 1em; color: rgb(186, 186, 186); position: absolute;" for="' + id + '">' + attrs.placeholder + '</label>');
element.attr('id', id).attr('shimmed', true).blur(update).focus(update).change(update).keydown(update).keyup(update);
$timeout(function() {
var pos = element.offset();
$document.find('body').eq(0).append(label);
label.css({
top: pos.top + 7,
left: pos.left + 13
});
});
scope.$on('$destroy', function(){
label.remove();
});
function update() {
if (element.val())
label.hide();
else {
label.show();
}
}
}
};
}
]);
})();
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment