如何获得 angular 指令的高度?
How do I get the height of an angular directive?
我花了一个多小时试图实现一些相当简单的事情:
创建一个angular指令,它可以获取和设置当前元素的高度。相同的指令应该可以访问 window(浏览器)以获得它的高度。
到目前为止,在测试时,我已经达到了这个(丑陋的)点:
myApp.directive("mainposter", function() {
return {
restrict: "E",
replace: false, //default is false, setting this to true has known bugs
//scope: {},
template: '<section class="mainposter">dummy text inside</section>',
link: function(scope, elem/*, attrs*/) {
/*elem.ready(function() {
console.log("the current height is: " + this.prop("tagName"))
})*/
console.log("the current tagname is: " + elem.prop("tagName"))
console.log("the current height is: " + elem.height())
}
}
})
目前我感兴趣的是只在页面加载时执行一次,而不是像这个解决方案那样连续执行:When to get the width of an Angular directive?
沮丧的 Angular 新手需要您的帮助。谢谢
编辑:
这个问题需要稍微不同的答案,因为 in this forum 他们提到 replace: true
有已知的错误问题
您可以使用 elem[0].clientHeight
或 elem[0].offsetHeight
来获取元素的高度。
link: function(scope, elem/*, attrs*/) {
/*elem.ready(function() {
console.log("the current height is: " + this.prop("tagName"))
})*/
console.log("the current tagname is: " + elem.prop("tagName"))
console.log("the current height is: " + elem[0].clientHeight);
}
你可以使用 jQuery $(elem).height()
确实jQuery对任务很有用。
设置replace: false
的元素高度为:$(elem[0].firstChild).height()
还有.outerHeight()
或.innerHeight()
,具体取决于您要准确计算的内容
你得到 window 的高度是这样的:
$(window).height()
我花了一个多小时试图实现一些相当简单的事情:
创建一个angular指令,它可以获取和设置当前元素的高度。相同的指令应该可以访问 window(浏览器)以获得它的高度。
到目前为止,在测试时,我已经达到了这个(丑陋的)点:
myApp.directive("mainposter", function() {
return {
restrict: "E",
replace: false, //default is false, setting this to true has known bugs
//scope: {},
template: '<section class="mainposter">dummy text inside</section>',
link: function(scope, elem/*, attrs*/) {
/*elem.ready(function() {
console.log("the current height is: " + this.prop("tagName"))
})*/
console.log("the current tagname is: " + elem.prop("tagName"))
console.log("the current height is: " + elem.height())
}
}
})
目前我感兴趣的是只在页面加载时执行一次,而不是像这个解决方案那样连续执行:When to get the width of an Angular directive?
沮丧的 Angular 新手需要您的帮助。谢谢
编辑:
这个问题需要稍微不同的答案,因为 in this forum 他们提到 replace: true
有已知的错误问题
您可以使用 elem[0].clientHeight
或 elem[0].offsetHeight
来获取元素的高度。
link: function(scope, elem/*, attrs*/) {
/*elem.ready(function() {
console.log("the current height is: " + this.prop("tagName"))
})*/
console.log("the current tagname is: " + elem.prop("tagName"))
console.log("the current height is: " + elem[0].clientHeight);
}
你可以使用 jQuery $(elem).height()
确实jQuery对任务很有用。
设置replace: false
的元素高度为:$(elem[0].firstChild).height()
还有.outerHeight()
或.innerHeight()
,具体取决于您要准确计算的内容
你得到 window 的高度是这样的:
$(window).height()