0

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?

7
  • Is that all HTML do you have? Commented Dec 17, 2018 at 13:20
  • @PrashantPimpale No, but that's the essential part where I call the function. The elements to add the css are also created dynamically. Commented Dec 17, 2018 at 13:22
  • is created dynamically gets created? Commented Dec 17, 2018 at 13:23
  • Yes. I creat them after clicking on the same element. That are these functions: getObjects($event); loadObj($event); Commented Dec 17, 2018 at 13:24
  • can loadObj($event); be asynchronous ? Commented Dec 17, 2018 at 13:30

1 Answer 1

1

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.

Sign up to request clarification or add additional context in comments.

1 Comment

Thanks, that helped a lot!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.