angularjsdatarepeater

Angularjs ng-repeat: how to detect a collection vs an array


I need to repeat over either a collection or an array, depending on the situation.

How Would I do that, provided the following approach causes "ngRepeat: dupes", code snippet as follows:

<div ng-if="cause.length" ng-repeat="k in cause">
    {{k}}
</div>
<div ng-if="!cause.length" ng-repeat="(k,v) in cause">
    {{k}}
</div>

Solution

  • add track by $index to end of ng-repeat declaration any you will not get any Dupes error...

    <div ng-if="cause.length" ng-repeat="k in cause track by $index">
        {{k}}
    </div>
    <div ng-if="!cause.length" ng-repeat="(k,v) in cause track by $index">
        {{k}}
    </div>
    

    UPDATE

    If no tracking function is specified the ng-repeat associates elements by identity in the collection. It is an error to have more than one tracking function to resolve to the same key. (This would mean that two distinct objects are mapped to the same DOM element, which is not possible.)

    and this explanation from angularjs documentation explains why it resolve this error...