angularjsangularjs-scopeangularjs-ng-init

Increment a counter based on number of elements


I have a below snippet for showing TABS which is static HTML. But each item would get shown on UI based on some business logic. Based on the number of tabs I need to set a width. For e.g if two tabs are shown then I need to equally divide tabs i.e 50%. when three, it will be 33.3%.

 <ul>
    <li>1</li>
    <li>2</li>
    <li>3</li>
    <li>4</li>
 </ul>

Using 'ng-class' I can add runtime classes to apply the width but its increasing the complexity and killing the page as I need to apply the same business logic in ng-class.

Rather, I was trying to use ng-init to get the count to check how many tabs are formed.

 <ul ng-init="totalTabs=0">
    <li ng-init="totalTabs=totalTabs+1">1</li>
    <li ng-init="totalTabs=totalTabs+1">2</li>
    <li ng-init="totalTabs=totalTabs+1">3</li>
    <li ng-init="totalTabs=totalTabs+1">4</li>
</ul>

This doesn't give me the expected count. Do you have any clue or suggestions ?


Solution

  • It's time to use some new features of CSS3. In case you don't know it, there's a new display called flex. It allows a lot of things, and one of them is to give elements the same width, based on their parent's width.

    You can find a quick tutorial here, or if you want to be fast :

    ul {
        display: flex;
        flex-flow: row wrap;
        justify-content: center;
        align-items: center;
        align-content: flex-start;
        li {
            flex: 1 1 auto;
        }
    }