angular.js ng-repeat - check if conditional is tru

2019-01-19 17:35发布

问题:

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!

回答1:

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



回答2:

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



回答3:

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