Home > Uncategorized > AngularJS Clearable Input Directive

AngularJS Clearable Input Directive

I wanted a clearable input field. It is supposed to show a close icon when input is typed into the input field. It was inspired by the following discussion on stackoverflow.

It consists of three parts:

1) The image for the close icon. Just take any one you like. I used this one. cross
2) The required CSS.

.clearable {
    background: url(/images/icons/cross.png) no-repeat right 5px center;
}
 
.clearable.onX {
    cursor: pointer;
}

3) The required AngularJS directive

app.directive('clearable', function($parse) {
    var link = function link(scope, element, attrs) {
        element.on('click', function() {
            if (element.hasClass("onX")) {
                scope.$apply(function(scope) {
                    $parse(attrs.clearable).assign(scope, null);
                });
            }
        });
 
        scope.$watch(attrs.clearable, function(val) {
            //console.log("Value is now: " + val);
            if (val) {
                element
                    .addClass('clearable')
                    .on('mousemove.clearable', function(event) {
                        if (this.offsetWidth - 18 < event.clientX - this.getBoundingClientRect().left) {
                            element.addClass('onX');
                        } else {
                            element.removeClass('onX');
                        }
                    });
            } else {
                element
                    .removeClass('clearable')
                    .off('mousemove.clearable');
            }
        });
    };
 
    return {
        restrict: "A",
        replace: false,
        transclude: false,
        link: link
    };
});

Use it by adding the following attribute to an input element:

<input type="text" ng-model="valueToObserve" clearable="valueToObserve" />

It will look like this.
clearable_input

Categories: Uncategorized Tags:
  1. No comments yet.
  1. No trackbacks yet.

Time limit is exhausted. Please reload CAPTCHA.