是否可以将'required'传递给AngularJS指令?

kre*_*eek 5 javascript validation angularjs

我正在制作一个使用<input>内部的自定义自动完成指令,但是我在确定如何将'required'属性传递下来时遇到了一些麻烦,其他具有我可以看到但是'required'的值的属性似乎无论是否设置都是空白的.我的回复声明的第一部分如下:

return {
            restrict: 'E',
            template: tpl,
            replace: true,
            scope: {
                suggestionsPath: '=autoComplete',
                method: '@method',
                term: '@term',
                required: '@required',
                ngModel: "="
            }...
Run Code Online (Sandbox Code Playgroud)

谢谢!

Chr*_*ola 4

我已经构建了一些输入扩展,扩展现有 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.
        }
Run Code Online (Sandbox Code Playgroud)

我建议您尽可能熟悉指令设计,因为自定义输入可能会变得非常棘手,具体取决于它们的用途(我们构建了自定义输入,添加了 +/- 按钮以及将数字格式化为百分比、货币或仅使用数字的输入键入时使用逗号)。除了 ngModelController 文档之外,这些文档对于查看也很有用: