Jan*_*nis 115 jquery dom callback document-ready angularjs
我有一个看似简单的问题,没有明显的(通过阅读Angular JS文档)解决方案.
我有一个Angular JS指令,它根据其他DOM元素的高度进行一些计算,以定义DOM中容器的高度.
类似于此的东西在指令内部发生:
return function(scope, element, attrs) {
$('.main').height( $('.site-header').height() - $('.site-footer').height() );
}
Run Code Online (Sandbox Code Playgroud)
问题是,当指令运行时,$('site-header')
无法找到,返回一个空数组而不是我需要的jQuery包装DOM元素.
是否有我可以在我的指令中使用的回调只在DOM加载后运行,我可以通过正常的jQuery选择器样式查询访问其他DOM元素?
Art*_*eev 137
这取决于你的$('site-header')的构造方式.
您可以尝试使用$ timeout和0延迟.就像是:
return function(scope, element, attrs) {
$timeout(function(){
$('.main').height( $('.site-header').height() - $('.site-footer').height() );
});
}
Run Code Online (Sandbox Code Playgroud)
不要忘记注入$timeout
你的指令:
.directive('sticky', function($timeout)
Run Code Online (Sandbox Code Playgroud)
rjm*_*226 44
我是这样做的:
app.directive('example', function() {
return function(scope, element, attrs) {
angular.element(document).ready(function() {
//MANIPULATE THE DOM
});
};
});
Run Code Online (Sandbox Code Playgroud)
jna*_*llo 37
可能作者不再需要我的答案了.尽管如此,为了完整起见,我觉得其他用户可能会发现它很有用.最好和最简单的解决方案是$(window).load()
在返回函数的主体内部使用.(或者你可以使用document.ready
.这取决于你是否需要所有图像).
$timeout
在我的拙见中使用是一个非常弱的选择,在某些情况下可能会失败.
这是我使用的完整代码:
.directive('directiveExample', function(){
return {
restrict: 'A',
link: function($scope, $elem, attrs){
$(window).load(function() {
//...JS here...
});
}
}
});
Run Code Online (Sandbox Code Playgroud)
有一个ngcontentloaded
事件,我想你可以使用它
.directive('directiveExample', function(){
return {
restrict: 'A',
link: function(scope, elem, attrs){
$$window = $ $window
init = function(){
contentHeight = elem.outerHeight()
//do the things
}
$$window.on('ngcontentloaded',init)
}
}
});
Run Code Online (Sandbox Code Playgroud)
如果由于外部资源而无法使用$ timeout,并且由于时间的特定问题而无法使用指令,请使用broadcast.
添加$scope.$broadcast("variable_name_here");
所需的外部资源或长时间运行的控制器/指令完成后.
在加载外部资源后添加以下内容.
$scope.$on("variable_name_here", function(){
// DOM manipulation here
jQuery('selector').height();
}
Run Code Online (Sandbox Code Playgroud)
例如,在延迟HTTP请求的承诺中.
MyHttpService.then(function(data){
$scope.MyHttpReturnedImage = data.image;
$scope.$broadcast("imageLoaded");
});
$scope.$on("imageLoaded", function(){
jQuery('img').height(80).width(80);
}
Run Code Online (Sandbox Code Playgroud)
归档时间: |
|
查看次数: |
128575 次 |
最近记录: |