linyuanxie
linyuanxie

Reputation: 787

How to access element in Angular directive?

I am trying to set the element's css property top base on it's height. To do it I create a directive like this:

directive('errormsgbox', function($timeout) {
    return {
        restrict: 'EA',
        scope: false,
        replace:true,
        templateUrl: 'submitter/reports/errormsgbox.html',
        link: function(scope,element) {
            $timeout(function(){
                    $timeout(function(){
                        console.log(element[0].offsetHeight);   

                },2000);
            },2000)    
        }
    };
})

Directive Html:

<span ng-if='expenses.hasBlockers || expenses.hasWarnigs' style='border:1px solid gray' ng-show='policyViolation && showpencil' class='msgbox'>
    <ul>
        <li ng-repeat='policymsg in expenses.policyMsg'>
            <span class='floatleft' ng-class="showPolicyClass(policymsg.type)">{{policymsg.type}} - </span><span style='width:285px;' class='floatleft'>{{policymsg.message}}</span>
            <div class='clear'></div>
        </li>
    </ul>
</span> 

Main Html:

<td class="text-center" style='position:relative'>
    <errormsgbox></errormsgbox>
</td>// it is in a table cell, the content of directive is from ng-repeat in this table

I need to access <span>.but as you can see, directive works fine it will show the correct info, but every time it will log undefined for element height. any idea How can I access this?

Upvotes: 1

Views: 240

Answers (2)

jrkt
jrkt

Reputation: 2715

Right click on the page that has the directive you want to access and click 'Inspect Element', then enter:

angular.element($0).scope()

in your developer console. This lets you access all the data in your angular scope. This will help debug the data that angular is using. But, in more direct answer to your question, I have done something similar where I set css properties inside a directive. It would turn your code into something like this:

return {
    restrict: 'EA',
    scope: false,
    replace:true,
    templateUrl: 'submitter/reports/errormsgbox.html',
    link: function(scope,element,attr) {
        element.css({
                    width: '360px',
                    height: '640px',
                    position: 'absolute',
                    top: '0px',
                    left: '0px',
                    background: '#FFF'
                }); 
    }
};

Upvotes: 1

scniro
scniro

Reputation: 16979

For E directives such as <my-dir></my-dir> the default display value will set to inline. You can do a few things here, either leverage block elements with replace: true or simply set a style rule, in this example, my-dir { display: block }. You could even call elem.css('display', 'block') in your directive link function.

JSFiddle Example - simplified demo


Keep in mind float rules along with inline-block will take margins and padding into consideration for examining offsetHeight

Upvotes: 1

Related Questions