我已经为输入构建了一些扩展,并且扩展现有 ngModel 绑定的最佳(可以说)唯一方法是在指令中使用 ngModelController。您可以使用“require”属性来要求另一个指令的控制器。ngModelController的文档在这里
这将允许您获取/设置模型值以及根据需要扩展或替换验证行为。因为您现在可能正在扩展 AngularJS 输入指令的组合,您可能还想查看 AngularJS 中的输入指令以了解其工作方式的示例。它们还可以与 ngFormController 作为整个表单的父级相切工作。这花了我一段时间来掌握,所以请耐心等待,但这是迄今为止最好的方法。
我会避免在这里隔离作用域,它们可能很棘手,并不总是与其他指令配合得很好(所以通常只在新元素或只有一个指令本身存在的事物上使用它)。我会设计这样的东西:
return {
restrict: 'E',
template: tpl,
replace: true,
require: 'ngModel',
link: function(scope, element, attrs, ngModelController) {
// Use attrs to access values for attributes you have set on the lement
// Use ngModelController to access the model value and add validation, parsing and formatting
// If you have an attribute that takes an expression you can use the attrs value along with $scope.$watch to check for changes and evaluate it or the $parse service if you just want to evaluate it.
}
我建议尽可能熟悉指令设计,因为自定义输入可能会变得非常棘手,具体取决于它们的作用(我们已经构建了添加 +/- 按钮的自定义输入,以及将数字格式化为百分比、货币或只是数字的输入)输入时使用逗号)。除了 ngModelController 文档之外,这些文档对查看也很有用: