Search code examples
angularjsangularjs-ng-repeat

angularjs how to increment init variable value in ng-repeat without onclick?


How to increment init variable value in ng-repeat

   <div ng-if="feedData.carouselMode == true" ng-init='start=0'  ng-repeat="a in carousel_data">

            <div  class="owl-demo" class="owl-carousel"   owl-carousel >
            <div class="item"  ng-repeat="(key, item) in a.carouselFeeds" ng-init="start=start+1">
                {{start}}
                <div ng-click="go('{{key}}', item.feedUrls.length, 'rtl')" ng-swipe-left="go('{{key}}', item.feedUrls.length, 'rtl')">
            <img class="lazyOwl"  ng-src="{{item.img}}"  />  
            <span class="innersquare" image-ja="{{item.img}}"> 
                <p ng-style="folderStyle">{{item.name  }}&nbsp;</p> </span>
                 </div> 
            </div>
        </div>
    </div>

ng-init start=0 after increment start=start+1 in ng-repeat but no count only show 1.


Solution

  • This is because each ng-repeat has its own scope and each ng-init will just increase its own scoped variable. You can try access the parent scope with $parent.

    In case you are looking for a continuous numeration try this

    <div ng-controller="MyCtrl">
    <div ng-repeat="a in ['a','b','c']" ng-init="current = $parent.start; $parent.start=$parent.start+3;">
            <div ng-repeat="x in ['alpha','beta','gamma']">
                {{current + $index}}
        </div>
    </div>
    

    Where the +3 should be +[LENGTH OF INNER ARRAY].

    http://jsfiddle.net/rvgvs2jt/2/

    For your specific code it would look like this

    <div ng-if="feedData.carouselMode == true" ng-init='current=$parent.start; $parent.start=$parent.start+a.carouselFeeds.length' ng-repeat="a in carousel_data">
        <div class="owl-demo" class="owl-carousel" owl-carousel>
            <div class="item" ng-repeat="(key, item) in a.carouselFeeds">
                {{current + $index}}
                <div ng-click="go('{{key}}', item.feedUrls.length, 'rtl')" ng-swipe-left="go('{{key}}', item.feedUrls.length, 'rtl')">
                    <img class="lazyOwl" ng-src="{{item.img}}" />
                    <span class="innersquare" image-ja="{{item.img}}"> 
                    <p ng-style="folderStyle">{{item.name  }}&nbsp;</p> </span>
                </div>
            </div>
        </div>
    </div>