How to create a custom input type?

后端 未结 3 1578
半阙折子戏
半阙折子戏 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: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.

提交回复
热议问题