How to create a custom input type?

后端 未结 3 1556
半阙折子戏
半阙折子戏 2020-12-01 10:52

I would like to create a custom input type similar to the way AngularJS implements \"email\", for example.



        
相关标签:
3条回答
  • 2020-12-01 11:32

    An alternative solution can be achieved by using the $parsers property of the ngModelController. This property represents a chain of parsers that are applied to the value of the input component before passing them to validation (and eventually assigning them to the model). With this, the solution can be written as:

    module.directive('input', function() {
        return {
            restrict: 'E',
            require: 'ngModel',
            link: function (scope, element, attr, ngModel) {
              if (attr.type !== 'path') return;
    
              ngModel.$parsers.push(function(v) {
                return v.replace(/\\/g, '/');
              });
            }
        };
    });
    

    Note that there is another property $formatters which is a pipeline of formatters that transform a model value into the value displayed in the input.

    See here for the plunker.

    0 讨论(0)
  • 2020-12-01 11:35

    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, '/');
    
                scope.$apply(function () {
                  ngModel.$setViewValue(path);
                });
              });
            }
        };
    });
    

    Example

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

    0 讨论(0)
  • 2020-12-01 11:36

    Considering compile function is the first in line, would it not be better with:

    module.directive('input', function() {
      return {
        restrict: 'E',
        require: 'ngModel',
        compile: function Compile(tElement, tAttrs) {
          if (tAttrs.type !== 'path') return;
    
          return function PostLink(scope, element, attr, ngModel) {
            // Override the input event and add custom 'path' logic
            element.unbind('input');
            element.bind('input', function () {
              var path = this.value.replace(/\\/g, '/');
    
              scope.$apply(function () {
                ngModel.$setViewValue(path);
              });
            });
          }
        }
      };
    });
    
    0 讨论(0)
提交回复
热议问题