【问题标题】:Angularjs show-errors directive with dynamic input具有动态输入的 Angularjs 显示错误指令
【发布时间】:2014-08-26 21:05:57
【问题描述】:

我正在使用 Paul Yoder 的 angular-bootstrap-show-errors 指令巧妙地切换表单组上的“有错误”类。这很好用,除非我的表单组的内容包含一个使用模板呈现其输入的指令,比如预输入。相关代码在这里:

angular.module('ui.bootstrap.showErrors', [])
    .directive 'showErrors', ['$timeout', ($timeout) ->
        linkFn = (scope, el, attrs, formCtrl) ->
        blurred = false
        inputEl = el[0].querySelector("[name]")
        inputNgEl = angular.element(inputEl)
        inputName = inputNgEl.attr('name')
        unless inputName
           throw "show-errors element has no child input elements with a 'name' attribute"

       inputNgEl.bind 'blur', ->
           blurred = true
           el.toggleClass 'has-error', formCtrl[inputName].$invalid
       scope.$watch ->
           formCtrl[inputName].$invalid
           , (invalid) ->
              return if !blurred && invalid
              el.toggleClass 'has-error', invalid

       scope.$on 'show-errors-check-validity', ->
           el.toggleClass 'has-error', formCtrl[inputName].$invalid
       scope.$on 'show-errors-reset', ->
           $timeout ->
               # want to run this after the current digest cycle
               el.removeClass 'has-error'
               blurred = false
               , 0, false
    {
        restrict: 'A'
        require: '^form'
        compile: (elem, attrs) ->
        unless elem.hasClass 'form-group'
            throw "show-errors element does not have the 'form-group' class"
        linkFn
    }
]

我的示例表单如下所示:

<div class="form-group" show-errors>
    <cool-control />
</div>

这个错误总是被抛出,因为在评估代码时,输​​入元素还不存在。有没有办法在子指令完成渲染后更改此选择的时间或重新评估它?

【问题讨论】:

  • 严格来说不是你的答案,但谷歌把我带到了这里。我试图在页面上多次放置的指令中使用show-errors。诀窍是使用 ng-form 指令 - 请参阅 stackoverflow.com/a/14379763/1141876

标签: angularjs angularjs-directive


【解决方案1】:

最终的解决方案是使用$timeout 函数将我的link 方法包装为指令,确保在DOM 渲染后发生事件绑定。

作为对遇到此问题的人的警告,在回答此问题时,Angular 中存在一个微妙的错误,涉及远程加载的指令模板在 link 函数执行之前未呈现。有关更多信息,请参阅此问题:Why is the post link function executed before the transcluded child link functions?

【讨论】:

猜你喜欢
  • 1970-01-01
  • 2014-02-14
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多