在 dom 完成渲染后如何运行指令? [英] How can I run a directive after the dom has finished rendering?

查看:34
本文介绍了在 dom 完成渲染后如何运行指令?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个看似简单的问题,但没有明显的(通过阅读 Angular JS 文档) 解决方案.

I've got a seemingly simple problem with no apparent (by reading the Angular JS docs) solution.

我有一个 Angular JS 指令,它根据其他 DOM 元素的高度进行一些计算,以定义 DOM 中容器的高度.

I have got an Angular JS directive that does some calculations based on other DOM elements' height to define the height of a container in the DOM.

指令内部发生了类似的事情:

Something similar to this is going on inside the directive:

return function(scope, element, attrs) {
    $('.main').height( $('.site-header').height() -  $('.site-footer').height() );
}

问题是当指令运行时,$('site-header') 找不到,返回一个空数组,而不是我需要的 jQuery 包装的 DOM 元素.

The issue is that when the directive runs, $('site-header') cannot be found, returning an empty array instead of the jQuery wrapped DOM element I need.

是否有可以在我的指令中使用的回调,该回调仅在 DOM 加载后运行,并且我可以通过普通的 jQuery 选择器样式查询访问其他 DOM 元素?

Is there a callback that I can use within my directive that only runs after the DOM has been loaded and I can access other DOM elements via the normal jQuery selector style queries?

推荐答案

这取决于你的 $('site-header') 是如何构建的.

It depends on how your $('site-header') is constructed.

您可以尝试使用 $timeout 和 0 延迟.类似的东西:

You can try to use $timeout with 0 delay. Something like:

return function(scope, element, attrs) {
    $timeout(function(){
        $('.main').height( $('.site-header').height() -  $('.site-footer').height() );
    });        
}

工作原理说明:one两个.

不要忘记在指令中注入 $timeout:

Don't forget to inject $timeout in your directive:

.directive('sticky', function($timeout)

这篇关于在 dom 完成渲染后如何运行指令?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆