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

会有一股神秘感。 提交于 2019-11-28 12:16:30

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

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

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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!