javascript - 在 div 中验证动态生成的输入

标签 javascript angularjs angularjs-directive

我正在尝试验证动态生成的输入,但我不知道该怎么做。

当我添加触发指令并动态插入输入的 div 时,div 添加了“has-error”类,但不应用输入样式任何人都知道最好的方法去做我想做的事?

这是标记:

<div ng-if="conditionItem.field.id"
     ng-class="{true: 'has-error'}[conditionItem.field.hasError]"
     dynamic
     input-router
     source="conditionItem.field"
     ng-click="FieldConditionsCtrl.valueTest(conditionItem.field.hasError)"
     ng-required="true"
     ng-model="conditionItem.situation[$index]">
</div>

这是如何生成输入的指令:

(function() {
  'use strict';

  angular
    .module('applicationInputs', ['rzModule', 'focus-if', 'ui.utils.masks'])
      .directive('inputRouter', inputRouter);

    /** @ngInject */
    function inputRouter($compile){
        return {
            restrict: 'EA',
            scope: {
                ngModel: '=',
                source: '=',
                placeholder: '@',
                tabIndex: '='
            },
            link: function(scope, element, attrs) {
                var canvas = angular.element(element[0]);
                scope.source.editable = angular.isUndefined(scope.source.editable) ? true : scope.source.editable === true;

                //used by setting to override selected field
                if (angular.isDefined(attrs.dynamic)) {
                    scope.$watch('source', function () {
                        var html = '<' + scope.source.type + 'input></' + scope.source.type + 'input>';
                        canvas.children().detach();
                        canvas.append($compile(html)(scope));
                    });

                } else {
                    var html = '<' + scope.source.type + 'input></' + scope.source.type + 'input>';
                    canvas.append($compile(html)(scope));
                }
            }
        }
    }
})();

这是我的风格:

.has-error {
     border-color: red
}

最佳答案

尝试边框:1px纯红色;而不仅仅是设置边框颜色。边框宽度默认为0,所以仅仅设置颜色是不够的

还有一些挑剔的主观风格评论:

  • 元素已经是一个jqLit​​e/jquery元素,所以不需要调用angular.element
  • scope.source.editable === true 赋值可以缩短为 !!scope.source.editable 如果你真的希望它是一个 bool 值。
  • 虽然聪明,但这种 jquery 风格的元素构建通常是 angular js 中的代码味道。如果你真的想走这条路,我会为你的输入构建独立的指令并使用 inputRouter 的模板来选择。它更容易理解,所以你 future 的自己会感谢你
  • {true: 'has-error'}[conditionItem.field.hasError] 花了我一分钟时间。写成 {conditionItem.field.hasError: 'has-error'}

我非常喜欢这些 AngularJS 风格指南:

有重叠,但可以从中取你喜欢的东西。

关于javascript - 在 div 中验证动态生成的输入,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54948106/

相关文章:

angularjs - 验证部署 : FAILED using MUP for my meteor app

angularjs - 类型错误 : Object doesn't support property or method 'setHost'

javascript - 如果所有模型值不为空则显示 Angular

javascript - Node.js MongoDB .findOne 在查询字符串时返回最佳匹配

javascript - 使用 javascript 根据 data-html 将类附加到元素

javascript - 如何使用 AJAX 和 PHP 迭代将 JSON 数据保存到新的 JSON 文件?

javascript - 如何使用此条件更新 MongoDB 中的约 20,000 条记录

javascript - AngularJS 1,什么逻辑决定输出去向?

angularjs - Angular 指令未在 ionic 应用程序中呈现

javascript - 指令在删除后获取其他指令的数据