验证div中动态生成的输入

时间:2019-03-01 15:53:09

标签: javascript angularjs angularjs-directive

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

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

这是标记:

> library(lubridate)
> 
> dates <- c(as.Date("2017-12-31"), as.Date("2016-12-31"))
> 
> y <- as.Date("2016-12-31")
> z <- as.Date("2017-12-31")
> 
> leap_every_year <- function(x) {
+   
+   ifelse(yday(x) > 59 & leap_year(x) == FALSE, yday(x) + 1, yday(x))
+   
+ }
> 
> leap_every_year(y)
[1] 366
> leap_every_year(z)
[1] 366
> leap_every_year(dates)
[1] 366 366

以下是如何生成输入的指令:

<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));
                }
            }
        }
    }
})();

1 个答案:

答案 0 :(得分:3)

尝试边框:1px稳定红色;而不是仅设置边框颜色。边框宽度默认为0,因此仅设置颜色是不够的

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

  • element已经是一个jqLit​​e / jquery元素,因此无需调用angular.element
  • 如果您真的希望它是布尔值,则可以将scope.source.editable ===真正的赋值缩短为!! scope.source.editable。
  • 虽然巧妙,但这种jquery样式元素的构建通常是angular js中的代码味道。如果您真的想走这条路,我将为您的输入构建独立的指令,并使用inputRouter的模板进行选择。它更容易理解,因此您未来的自我会感谢您
  • {true:“存在错误”} [conditionItem.field.hasError]花了我几分钟。只需将其写为{conditionItem.field.hasError:'has-error'}

我非常喜欢AngularJS的这些样式指南:

有重叠之处,但各取所需。

相关问题