简体   繁体   中英

How do I get the height of an angular directive?

I have spent more than an hour trying to achieve something fairly simple:
Create an angular directive which can get and set the height of the current element. The same directive should have access to the window (browser) in order to get its height.

So far, while testing, I have reached up to this (ugly) point:

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())
    }
  }
})

Currently I am interested in having this executed only once on page load and not continuously like this solution: When to get the width of an Angular directive?

The frustrated Angular newbie needs your help. Thank you

EDIT: This question needs a slightly different answer because in this forum they are mentioning that replace: true has known bug issues

You can use elem[0].clientHeight or elem[0].offsetHeight to get the height of the element.

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()

Indeed jQuery is useful for the task.

The height of the element with the settings replace: false is: $(elem[0].firstChild).height()
also .outerHeight() or .innerHeight() depending on what you want to calculate exactly

You get the height of the window like this:
$(window).height()

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM