Skip to content

Instantly share code, notes, and snippets.

@kennyki
Created July 28, 2015 09:33
Show Gist options
  • Star 2 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save kennyki/35578c24a854923484e2 to your computer and use it in GitHub Desktop.
Save kennyki/35578c24a854923484e2 to your computer and use it in GitHub Desktop.
AngularJS directive for `autocomplete=off` (that works.. so far)
angular.module('dont_fill', [])
// cross-browser trick to prevent input being auto-filled
// where autocomplete=off don't work as intended a lot of time
.directive('dontFill', function() {
return {
restrict: 'A',
link: function link(scope, el, attrs) {
// password fields need one of the same type above it (firefox)
var type = el.attr('type') || 'text';
// chrome tries to act smart by guessing on the name.. so replicate a shadow name
var name = el.attr('name') || '';
var shadowName = name + '_shadow';
// trick the browsers to fill this innocent silhouette
var shadowEl = angular.element('<input type="' + type + '" name="' + shadowName + '" style="display: none">');
// insert before
el.parent()[0].insertBefore(shadowEl[0], el[0]);
}
};
})
;
@santosh-k1
Copy link

Use autocomplete="false" in ng-form to desibled auto complete

@ithan1985
Copy link

ithan1985 commented Sep 3, 2017

this is the cure thanks so much

@WuglyakBolgoink
Copy link

Use autocomplete="false" in ng-form to desibled auto complete

doesn't work on 2021)

@kennyki
it will be better to add $interpolate(el.attr('name') || '')(scope) if any input field hast dynamic naming:

my ES6 version:

'use strict';

/**
 * @class DontFill
 *
 * cross-browser trick to prevent input being auto-filled
 * where autocomplete=off don't work as intended a lot of time
 *
 * @type {angular.IDirective}
 *
 * @ngInject
 */
class DontFill {

    /**
     * @constructor
     */
    constructor() {
        this.restrict = 'A';
    }

    /**
     * @param {angular.IInterpolateService} $interpolate - Service.
     *
     * @ngInject
     */
    controller(
        $interpolate
    ) {
        this._$interpolate = $interpolate;
    }

    link(scope, el, attr, ctrl) {
        // password fields need one of the same type above it (firefox)
        const type = el.attr('type') || 'text';

        // chrome tries to act smart by guessing on the name.. so replicate a shadow name
        const name = ctrl._$interpolate(el.attr('name') || '')(scope) || '';

        // trick the browsers to fill this innocent silhouette
        const shadowEl = angular.element(`<input type="${ type }" name="${ `${ name }_shadow` }" style="display: none">`);

        // insert before
        el.parent()[0].insertBefore(shadowEl[0], el[0]);
    }

}

angular
    .module('dont_fill', [])
    .directive('dontFill', () => {
        return new DontFill();
    });

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment