-
Notifications
You must be signed in to change notification settings - Fork 11
/
angular.dcb-clear-input.js
47 lines (44 loc) · 1.87 KB
/
angular.dcb-clear-input.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
/*
Angular Clear Input directive
(c) 2014 Daniel Cohen. http://dcb.co.il
License: MIT
*/
angular.module('dcbClearInput', [])
.directive('clearInput', ['$parse',
function($parse) {
return {
restrict: 'A',
require: 'ngModel',
link: function(scope, element, attr) {
var htmlMarkup = attr.clearBtnMarkup ? attr.clearBtnMarkup : '<span>X</span>';
var btn = angular.element(htmlMarkup);
btn.addClass(attr.clearBtnClass ? attr.clearBtnClass : "clear-btn");
element.after(btn);
btn.on('click', function(event) {
if (attr.clearInput) {
var fn = $parse(attr.clearInput);
scope.$apply(function() {
fn(scope, {
$event: event
});
});
} else {
scope[attr.ngModel] = null;
scope.$digest();
}
});
scope.$watch(attr.ngModel, function(val) {
var hasValue = val && val.length > 0;
if (!attr.clearDisableVisibility) {
btn.css('visibility', hasValue ? 'visible' : 'hidden');
}
if (hasValue && !btn.hasClass('clear-visible')) {
btn.removeClass('clear-hidden').addClass('clear-visible');
} else if (!hasValue && !btn.hasClass('clear-hidden')) {
btn.removeClass('clear-visible').addClass('clear-hidden');
}
});
}
};
}
]);