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

前端 未结 3 1970
悲哀的现实
悲哀的现实 2020-12-11 04:39

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 serv

相关标签:
3条回答
  • 2020-12-11 04:48

    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

    0 讨论(0)
  • 2020-12-11 04:53

    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

    0 讨论(0)
  • 2020-12-11 05:03

    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

    0 讨论(0)
提交回复
热议问题