我已经构建了一些扩展的输入,最好的(可以说)只有扩展现有的ngModel绑定的方法是在你的指令中使用ngModelController。您可以通过使用“require”属性来请求其他指令的控制器。 documentation for ngModelController is here
这将允许您获取/设置模型值以及根据需要扩展或替换验证行为。因为您现在可能在组合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文档,这些都是有用的审查:
你可以在你的指令的作用域中尝试'ng-required'而不是'ngRequired'。 – jpmorin
你也可以看看链接函数中'attrs.required'属性的内容,看看是否有什么东西。 – jpmorin
是否有你需要隔离范围的理由?看起来似乎更简单,但通常不是。我会建议不同的需要“ngModelController”并使用“attrs”和$ scope。$ watch如果你需要动态绑定。让我知道你是否想要一个更完整的解决方案,如果你发布了一个jsFiddle或者我会尽力帮忙的。 –