2013-02-06 81 views
16

我想创建一个类似于AngularJS实现“email”的自定义输入类型,例如。如何创建自定义输入类型?

<input type="email" ng-model="user.email" /> 

我想创建一个输入型是这样的:

<input type="path" ng-model="page.path" /> 

这是如何得来的任何想法?到目前为止,我只能弄清楚如何实现自定义指令,其中“路径”是标记,属性或类的名称。

例如,我可以得到这个工作,但它是不一致与其他表单字段,我真的很喜欢他们看起来一样。

<input type="text" ng-model="page.path" path /> 
app.directive('path', function() { 
    return { 
    require: 'ngModel', 
    link: function(scope, elm, attrs, ctrl) { ... } 
    }; 
}); 

回答

19

您可以创建自己的输入型=“路径”的,如果该类型属性设置为“路径”创建自定义逻辑输入指令。

我创建了一个简单的例子,它简单地用/代替\。该指令是这样的:

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

更新:改变onoffbindunbind删除jQuery的依赖。示例已更新。

+1

这为TYPE =“文件”的错误,因为角期待ngmodel现在 – Pascalius

+1

@Pascalius你可以改变需要一行来:'require:'?ngModel''不可以。 – Martin

+0

'off'和'on'是jQuery方法。这不会工作,除非你也有jQuery加载。 –

2

使用ngModelController$parsers属性可以实现替代解决方案。该属性表示一系列解析器,在将它们传递给验证(并最终将它们分配给模型)之前应用于输入组件的值。由此,溶液可被写为:

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, '/'); 
      }); 
     } 
    }; 
}); 

注意,还有另一种属性$formatters其为变换模型值到在该输入显示的值格式化的一个管道。

请参阅here为掠夺者。

0

考虑编译功能是排在第一位,岂不是更好:

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); 
      }); 
     }); 
     } 
    } 
    }; 
}); 
相关问题