hmd
hmd

Reputation: 970

Restrict AngularJS ng-style

I'm calculating containers heights as per viewport by ng-style through my custom method.

Everything works well, but it keeps calling the method even if the element is styled. I have a big amount of DOM elements that are need to be styled. That's why, I can't allow continuous execution for all elements. Please note, I can't use ng-class because each element contains different content. And can't use controller scope variable due to unlimited numbers of elements.

HTML:

<div class="myElement" ng-style="styleElement('myElement')">
    ...
    ...
</div>

Function:

$scope.styleElement =  function (elementCls) {
    var elementToSet = $('.'+elementCls+':visible');
    if(elementToSet.length){
        var winHeight = $( window ).height();
        var eTop = elementToSet.offset().top;
        if(eTop == 0){
            var elemChilds = elementToSet;
            var elemChildsLen = elemChilds.length;
            for(var i=0;i<elemChildsLen;i++){
                var elem = elemChilds[i];
                var r = elem.getBoundingClientRect();
                if(r.top != 0){
                    eTop = r.top;
                    i= elemChildsLen; 
                }
            }
        }
        var nScrollHeight = winHeight - eTop - 20;
        return { 
            'height': nScrollHeight + 'px',
            'overflow-x': 'hidden',
            'overflow-y': 'auto'
        };
    }
};

I've tried using a custom directive but binding DOM or writing a watcher isn't a preferable solution for me due to performance. Thanks in advance!

Upvotes: 0

Views: 57

Answers (1)

lacunha
lacunha

Reputation: 36

Use one time binding, which will only call styleElement once.

<div class="myElement" ng-style="::styleElement('myElement')">
    ...
    ...
</div>

Upvotes: 0

Related Questions