简体   繁体   中英

Ng-repeat and Ng-show in angular

I want to display only the first element in ng-repeat and by click display the rest elements.

That's what I tried to do without success:

<button data-ng-click="term = !term">Show rest</button>

    <div data-ng-repeat="y in mQues track by $index" data-ng-show="term" data-ng-init="term = $first"> 
    ...
    </div>

it really display only the first but the button click do noting for some reason...

更改您的ng-show条件: data-ng-show="term || $first"

尝试这个...

<div data-ng-repeat="item in items" data-ng-show="term || $index == 0">{{item.title}}</div>

 <div data-ng-repeat="y in mQues track by $index" data-ng-if="$first"></div> 

我认为这会有所帮助

Using the angular filter limitTo it is rather straight forward.

 function MyCtrl($scope) { $scope.items = [ { title: "item 1" }, { title: "item 2" }, { title: "item 3" }, { title: "item 4" } ] $scope.limit = 1; } 
 <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script> <div ng-app ng-controller="MyCtrl"> <span ng-click="limit = limit == 1 ? items.length : 1">Toggle</span> <ul> <li ng-repeat="item in items | limitTo:limit" ng-bind="item.title"></li> </ul> </div> 

https://docs.angularjs.org/api/ng/directive/ngShow

ng-show displays an element by evaluating the expression given to it.

the expression assigned to ng-show gets converted to true or false depending on whether the result is 'truthy' or 'falsy'. When you assign term a truthy value, ng-show is assigned true.

when you do click button, it evaluates term = !term and term then becomes false and therefore the whole div will be hidden

Guess simpler and more straight forward:

var app = angular.module('app', []);

app.controller('DisplayController', function($scope) {
  $scope.ShowRest = 0;
  $scope.items = [{
    title: 'myTitle1'
  }, {
    title: 'myTitle2'
  }, {
    title: 'myTitle3'
  }, {
    title: 'myTitle4'
  }, {
    title: 'myTitle5'
  }];
});

app.$inject = ['$scope'];

Then:

<div data-ng-controller="DisplayController">
  <div data-ng-repeat="item in items">
    <div data-ng-class="{'no-display': !$first}">{{ item.title }}</div>
  </div>
  <div data-ng-repeat="item in items" data-ng-show="ShowRest">
    <div data-ng-class="{'no-display': $first}">{{ item.title }}</div>
  </div>
  <button data- ng-click="ShowRest = !ShowRest">Show rest</button>
</div>

Maybe it's not the most efficient way of doing it, but it works! Fiddle: http://jsfiddle.net/cb6pggL8/1/

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM