directive clearInput
by Roman
HTML
<script src="https://code.angularjs.org/1.3.9/angular.min.js"></script>
<!-
Usgae: Add directive to container to add click to clear (and ESC key to clear). Add to container as:
clear-input [icon="any_bootstrap_icon"] [auto-hide="true|false"]
Defaults to glyphicon-remove and autoHide defaults to false.
-->
<div class="row" ng-app="myApp" style="padding: 1em">
<div class="col-xs-12">
<form role="form" clear-input auto-hide="true">
<div class="form-group">
<label for="email">Email address:</label>
<input type="text" class="form-control" id="name" ng-model="name">
</div>
<div class="form-group">
<label for="pwd">Password:</label>
<input type="password" class="form-control" id="pwd" ng-model="pass">
</div>
<div class="checkbox">
<label>
<input type="checkbox">Remember me</label>
</div>
<button type="submit" class="btn btn-default">Submit</button>
<br>
<br>Name: {{name}}
<br>Pass: {{pass}}</form>
</div>
</div>
JavaScript
(function ($) {
"use strict";
angular.module('myApp', []).directive('clearInput', ['$log', function($log) {
function debug(msg) { $log.debug(directiveName + ": " + msg); }
return {
restrict: 'A',
scope: {
},
replace: true,
link: function ($scope, elem, attrs) {
var children = $(elem).find(':input'),
icon = attrs.icon || 'glyphicon-remove',
autoHide = attrs.autoHide || false,
inp = null,
disp, i, h, w, ih, iw, top, left, ix, child, div, type, newInput;
// Called on resize to adjust position if input resizes
function updatePosition(inp, i) {
var h, w, ih, iw, top, left;
h = inp.outerHeight();
w = inp.outerWidth();
ih = i.outerHeight();
iw = i.outerWidth();
i.css({
top: h / 2 - ih / 2,
left: w - 2 * ih,
color: 'Gray',
position: 'absolute',
display: 'inline-block',
'z-index': 1000
});
if (!inp.val() && autoHide) {
i.hide();
}
}
function makeClickHandler(elm, i) {
return function () {
elm.val('');
elm.trigger('input');
if (autoHide) {
i.hide();
}
};
}
function makeKeyHandler(elm, i) {
return function (e) {
if (e.keyCode && e.keyCode === 27) {
elm.val('');
elm.trigger('input');
...