Thursday, 16 December 2021

AngularJs directive for clearing a text field

I wrote an AngularJs directive at work today for clearing a text field. We still use this in multiple projects for front-end (although I have worked more with Angular than AngularJs last 2-3 years). The directive ended up like this (we use Bootstrap v2.3.2) :

angular.module('formModule').directive('addClearTextFieldBtn', function ($compile) {
        function link(scope, element, attrs) {
            var targetId = attrs.id;
            var targetNgModel = attrs.ngModel;
            var minimumChars = attrs.clearTextFieldBtnMintextlength ? attrs.clearTextFieldBtnMintextlength : "1";
            var emptyValue = "''";
            var templateAppend = '<i id="clear' + targetId + '" ng-if="' + targetNgModel + ' && + ' + targetNgModel + '.length >= ' + minimumChars + '"' + 'ng-click="' + targetNgModel;
            templateAppend += ' = ' + emptyValue + '" class="glyphicon icon-remove form-control-feedback" title="Tøm innhold" style="cursor:pointer; pointer-events: all;" tooltip="clear"></i >';
            var clearButton = angular.element(templateAppend);
            clearButton.insertAfter(element);
            $compile(clearButton)(scope);
        }
        return {
            restrict: 'A',
            replace: false,
            link: link
        };
    });

Example usage inside a HTML helper in MVC for example:
add_clear_text_field_btn = "model.Icd10", data_clear_text_field_btn_mintextlength="3"
We pass in a HTML5 data value attribute to specify the minimum length to show the button to clear the field.

Share this article on LinkedIn.

2 comments:

  1. Added HTML looks like this for example. Note the usage of the $compile service for AngularJs. This fixes those double ampersands for example.

    <i id="clearHoveddiagnose" ng-if="model.Hoveddiagnose && + model.Hoveddiagnose.length >= 3" ng-click="model.Hoveddiagnose = ''" class="glyphicon icon-remove form-control-feedback ng-scope" title="Tøm innhold" style="cursor:pointer; pointer-events: all;" tooltip="clear"></i>

    ReplyDelete
  2. Working as a freelancer exposes you to various work cultures and communication approaches when you deal with customers from various countries. A 9-to-5 remote java developer is cautious about taking on freelancing work because most companies do not allow their employees to do so. Eiliana is a renowned platform where you can find freelance remote java developer jobs, and this platform also assists you in maintaining secrecy.

    ReplyDelete