我刚刚得到了我的指令拉入一个模板,以附加到它的元素,像这样:
# CoffeeScript
.directive 'dashboardTable',->
controller: lineItemIndexCtrl
templateUrl: "<%= asset_path('angular/templates/line_items/dashboard_rows.html') %>"
(scope,element,attrs) ->
element.parent('table#line_items').dataTable()
console.log 'Just to make sure this is run'
# HTML
<table id="line_items">
<tbody dashboard-table>
</tbody>
</table>
我也使用一个名为DataTables的jQuery插件。它的一般用法是这样:$(‘table#some_id’)。dataTable()。你可以将JSON数据传递到dataTable()调用来提供表数据,或者你可以有数据已经在页面上,它会做剩下的。我做后者,已经在HTML页面上的行。
但问题是,我必须调用dataTable()在表#line_items AFTER DOM准备好。我的指令在模板附加到指令的元素之前调用dataTable()方法。有没有办法,我可以调用函数后附加?
感谢您的帮助!
更新1后Andy的答案:
我想确保链接方法只有在一切都在页面上后被调用,所以我改变了指令进行一点测试:
# CoffeeScript
#angular.module(...)
.directive 'dashboardTable',->
{
link: (scope,attrs) ->
console.log 'Just to make sure this gets run'
element.find('#sayboo').html('boo')
controller: lineItemIndexCtrl
template: "<div id='sayboo'></div>"
}
我确实看到“boo”在div#sayboo。
然后我尝试我的jquery datatable调用
.directive 'dashboardTable',attrs) ->
console.log 'Just to make sure this gets run'
element.parent('table').dataTable() # NEW LINE
controller: lineItemIndexCtrl
templateUrl: "<%= asset_path('angular/templates/line_items/dashboard_rows.html') %>"
}
没有运气
然后我尝试添加一个超时:
.directive 'dashboardTable',($timeout) ->
{
link: (scope,attrs) ->
console.log 'Just to make sure this gets run'
$timeout -> # NEW LINE
element.parent('table').dataTable(),5000
controller: lineItemIndexCtrl
templateUrl: "<%= asset_path('angular/templates/line_items/dashboard_rows.html') %>"
}
这工作。所以我想知道在非定时器版本的代码出了什么问题?
如果未提供第二个参数“delay”,则默认行为是在DOM完成呈现后执行该函数。所以,而不是setTimeout,使用$ timeout:
$timeout(function () {
//DOM has finished rendering
});