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

标签 javascript validation angularjs

我正在制作一个使用 <input> 的自定义自动完成指令本身,但我在弄清楚如何向下传递“必需”属性时遇到了一些麻烦,其他具有我可以看到的值但“必需”的属性无论是否设置都显示为空白。下面是我的返回声明的第一部分:

return {
            restrict: 'E',
            template: tpl,
            replace: true,
            scope: {
                suggestionsPath: '=autoComplete',
                method: '@method',
                term: '@term',
                required: '@required',
                ngModel: "="
            }...

谢谢!

最佳答案

我已经构建了一些输入扩展,扩展现有 ngModel 绑定(bind)的最佳(可以说)唯一方法是在指令中使用 ngModelController。您可以使用“require”属性来要求另一个指令的 Controller 。 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 文档之外,这些文档对于查看很有用:

关于javascript - 是否可以将 'required' 传递给 AngularJS 指令?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19371111/

相关文章:

javascript - 访问 DOM 元素时 window.element 和 element 之间有什么区别

javascript - 在焦点上添加一个属性

angularjs - 在 angularjs 中显示输入验证的弹出窗口

java - 静态内部类的 Hibernate 验证

javascript - Socket.emit无法触发socket.on

javascript - JavaScript 中的 If(条件 == 任意数组值)

javascript - Webpack 输出图像的错误路径

java - 如何自定义 javax 验证的区域设置

javascript - 来自 Partials 的 Angular JS $scope 在 index.html 中不起作用

javascript - Ng-Route 不适用于 Node/Express 静态服务器