temp
temp

Reputation: 571

Adding css after creating elements

I want to add some icons to elements I created with angularJS directly after creating them. So I am calling the function to set the icons at the same time the elements were created.

data-ng-click="opeTab($event); getObjects($event); loadObj($event); setIcons();"

The problem is, I can get the elements with:

    $scope.setIcons = function(){
    
    var tbs = document.getElementsByClassName("tabTr");
    
    for(let i = 0; i < tbs.length; i++){
        console.log(i);
        tbs[i].style.backgroundImage = "url('../ICONS\Icons_24\'" + tbs[i].id + "')";
        }
    }

And the list in the console is filled, but the length of the array is 0. So what possibility do I have to "wait" for the creation except setting a timeout?

Upvotes: 0

Views: 86

Answers (1)

Andrew Lahikainen
Andrew Lahikainen

Reputation: 370

You should try to avoid creating elements yourself from your controllers. Maybe you have a good reason for doing this, but I can't see that from the example you have given.

Somewhere in your template you should have an ng-repeat which renders your tabs. Each tab should have an ng-style. Lets say:

// template.html
<div class="tabs" ng-repeat="tab in tabs">
    <div
        class="tab"
        ng-style="getBackgroundImageStyle(tab.id)">
        tab {{ tab.id }}
    </div>
</div>

// controller.js
$scope.tabs = [];

$scope.getBackgroundImageStyle = tabId => `{
    'background-image': 'url('../ICONS/Icons_24/${tabId}')'
}`

$scope.openTab = () => {
    $scope.tabs.push(new Tab(nextTabId)); // or however you create your tabs
}

If you have a good reason for accessing the dom directly like this, then there is no problem using $timeout with a delay of 0 and wrapping your dom modification inside this. Everything should be rendered before the code inside your $timeout runs.

Upvotes: 1

Related Questions