How to create a custom input type?

You can create your own input type=”path” by creating an input directive with custom logic if the type attribute is set to “path”.

I’ve created a simple example that simply replaces \ with /. The directive looks like this:

module.directive('input', function() {
    return {
        restrict: 'E',
        require: 'ngModel',
        link: function (scope, element, attr, ngModel) {
          if (attr.type !== 'path') return;

          // Override the input event and add custom 'path' logic
          element.unbind('input');
          element.bind('input', function () {
            var path = this.value.replace(/\\/g, "https://stackoverflow.com/");

            scope.$apply(function () {
              ngModel.$setViewValue(path);
            });
          });
        }
    };
});

Example

Update: Changed on, off to bind, unbind to remove jQuery dependency. Example updated.

Leave a Comment