forked from dboskovic/angular-placeholder-polyfill
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathangular.placeholder.polyfill.js
89 lines (78 loc) · 3.46 KB
/
angular.placeholder.polyfill.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
(function () {
'use strict';
angular.module('app')
.directive('placeholder', ['$timeout', function ($timeout) {
return function(scope, el, attrs){
var settings = {
cssClass : 'placeholder',
excludedAttrs : ['placeholder', 'name', 'id', 'ng-model', 'type']
},
placeholderText = attrs.placeholder,
isPassword = attrs.type === 'password',
hasNativeSupport = 'placeholder' in document.createElement('input') && 'placeholder' in document.createElement('textarea'),
setPlaceholder, removePlaceholder, copyAttrs, fakePassword;
if(hasNativeSupport) return;
copyAttrs = function() {
var a = {};
$.each(attrs.$attr, function (i, attrName) {
if (!~$.inArray(attrName, settings.excludedAttrs)) {
a[attrName] = attrs[attrName];
}
});
return a;
};
var createFakePassword = function(){
return $('<input>', $.extend(copyAttrs(), {
'type': 'text',
'value': placeholderText
}))
.addClass(settings.cssClass)
.bind('focus', function () {
removePlaceholder();
})
.insertBefore(el);
};
if (isPassword) {
fakePassword = createFakePassword();
setPlaceholder = function(){
if(!el.val()){
fakePassword.show();
el.hide();
}
};
removePlaceholder = function(){
if(fakePassword.is(':visible')) {
fakePassword.hide();
el.show().focus();
}
};
} else {
setPlaceholder = function(){
if(!el.val()){
el.val(placeholderText);
$timeout(function(){
el.addClass(settings.cssClass); /*hint, IE does not aplly style without timeout*/
}, 0)
}
};
removePlaceholder = function(){
if (el.hasClass(settings.cssClass)) {
el.val('').select(); /*trick IE, because after tabbing focus to input, there is no cursor in it*/
el.removeClass(settings.cssClass);
}
};
}
el.on('focus', removePlaceholder).on('blur', setPlaceholder);
$timeout(function(){
el.trigger('blur');
}, 0);
scope.$watch(attrs.ngModel, function(value) {
if(value == ''){
if(!el.is(':focus')) el.trigger('blur')
} else {
if(el.hasClass(settings.cssClass)) el.removeClass(settings.cssClass)
}
});
}
}]);
}());