我使用Paul Yoder的angular-bootstrap-show-errors指令巧妙地切换了“错误”错误'我的表格组上的课程。除非我的表单组的内容包含使用模板呈现其输入的指令(如typeahead),否则这很有效。相关代码在这里:
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>
此错误总是被抛出,因为在评估代码时,输入元素尚未存在。有没有办法可以在子指令完成渲染后更改此选择的时间或重新评估它?
答案 0 :(得分:1)
最终解决方案是使用$timeout
函数来包装指令的link
方法,确保在呈现DOM之后发生事件绑定。
作为对遇到此问题的人的警告,在此回答时,Angular中存在一个微妙的错误,涉及在link
函数执行之前未呈现的远程加载的指令模板。有关详细信息,请参阅此问题:Why is the post link function executed before the transcluded child link functions?