0

I have two arrays. If ctrl.type == 'group' I want to do an ng-repeat

<div ng-repeat="category in ctrl.categories">
  ...
  <div ng-repeat="item in category.group_items">...</div>
</div>

else, it should be

<div ng-repeat="category in ctrl.categories">
  ...
  <div ng-repeat="item in category.data.other_items">...</div>
</div>

what's the best way to write this? I don't want to rewrite the ... as it's the same code.

2
  • Initialize a variable theItems with one or the other in your controller, and iterate through theItems. Commented Mar 28, 2018 at 18:07
  • @JBNizet I edited question to show it is in another ng-repeat, is it still best to do as you wrote? Commented Mar 28, 2018 at 18:09

2 Answers 2

2

Make a function that returns the array in your controller.

ctrl.getArray = () => {
  if(ctrl.type === 'something') {
    return ctrl.data.group_items;
  }

  return ctrl.data.other_items;
}

And in the view:

<div ng-repeat="item in ctrl.getArray()">...</div>
Sign up to request clarification or add additional context in comments.

Comments

1

It can also be done using ng-switch. Below is my controller code where i have defined two arrays and also defined type on which your data will be shown.

var app = angular.module('myApp', []);
app.controller('myCtrl', function($scope) {
     $scope.type = 'something';
    $scope.categories=[{ID:'1',Name:'Test 1'},{ID:'2',Name:'Test 2'},{ID:'3',Name:'Test 3'}];

     $scope.group_items=[{ID:'1',Name:'Group 1'},{ID:'2',Name:'Group 2'},{ID:'3',Name:'Group 3'}];

});

Below is the html bindings.

<div ng-app="myApp" ng-controller="myCtrl">    
    <div ng-switch="type">
        <div ng-switch-when="group">
           <div ng-repeat="item in categories">
              <p>{{item.Name}}</p>
           </div>
        </div>

        <div ng-switch-when="something">
           <div ng-repeat="item in group_items">
              <p>{{item.Name}}</p>
           </div>
        </div>        
    </div>    
</div>

Comments

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.