Kosmetika
Kosmetika

Reputation: 21304

angular.js ng-repeat - check if conditional is true then use another collection

I'm wondering is it possible to check what collection to use inside ng-repeat?

For example, in my controller I have 2 arrays of data fetched from server, now I use ng-switch to switch between them, check this jsbin - http://jsbin.com/diyefevi/1/edit?html,js,output

The problem is that these li views in my real application are big but very similar.. so I really would like to use 1 ng-repeat instead of 2.

So I wonder if something like ng-repeat="book in if list==='adultBooks' adultBooks else childBooks" is possible in Angular?

Thanks!

Upvotes: 8

Views: 30683

Answers (3)

Dalorzo
Dalorzo

Reputation: 20014

Try this ...

In your controller

$scope.getDataSource=function(condition){

  if(condition){ return dataSource1; }
  return dataSource2;
};

In your Html

ng-repeat="book in getDataSource(/*condition*/)

MVVM Pattern advises to put our logic always in the controller and not in the view(HTML). If you ever find yourself adding "logic" in your view probably there is an alternate "better" way to do it.

But just for "fun" you can do this too:

ng-repeat="book in {true: adultBooks, false: childBooks}[list==='adultBooks']"

Like this:

<li ng-repeat="book in {true: childBooks, false:adultBooks}[list==='childBooks']">{{book.name}

Here is the full sample:

http://jsbin.com/diyefevi/5/edit?html,js,output

Upvotes: 24

zszep
zszep

Reputation: 4458

Something like this would eliminate the need for ng-switch:

<!DOCTYPE html>
<html ng-app="test">
<head>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.14/angular.min.js"></script>
  <meta charset="utf-8">
  <title>JS Bin</title>
</head>
<body ng-controller="MainCtrl">
  <a href="" ng-click="toggleList()">Toggle List</a>
  <h1>{{list}}</h1>
  <ul>
      <li ng-repeat="book in getBooks()">{{book.name}}</li>
  </ul>
</body>
</html>

and the js:

var app = angular.module('test', []);
app.controller('MainCtrl', function ($scope) {
  $scope.list = 'childBooks';

  $scope.childBooks = [{name: 'Dodobird'}, {name: 'Catty Red Hat'}];

  $scope.adultBooks = [{name: 'Little Lady'}, {name: 'Johny Doe'}];

  $scope.toggleList = function () {
    $scope.list = $scope.list === 'childBooks' ? 'adultBooks' : 'childBooks';
  };

  $scope.getBooks = function() {
    if($scope.list == 'adultBooks') {
      return $scope.adultBooks;
    } else {
      return $scope.childBooks;
    }
  }
});

Here is the jsbin code

Upvotes: 2

Augier
Augier

Reputation: 311

The simplest solutions I can think of would be to define a new array on the scope which you set the other arrays to when you need.

E.g. http://jsbin.com/diyefevi/4/edit?html,js,output

Upvotes: 2

Related Questions