Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to show element once in ng-repeat

Tags:

angularjs

I need to loop through a list order by price and as soon as the price is not there then I show a message with unavailable but I don't want to show it for each empty element. I'm using angular 1.2

<div ng-repeat="item in list | orderBy: 'cost'">

  <div ng-if="cost == 0 and not already shown">Sorry the following are unavailable</div>
  <div>...my item here...</div>
<div>
like image 721
matthewdaniel Avatar asked May 12 '15 15:05

matthewdaniel


3 Answers

You can conditionally display two spans - one if it's 0 (your 'not available' message) and another for anything else.

<ul>
  <li ng-repeat="d in newData track by $index">
    <span ng-show="d > 0">{{d}}</span>
    <span ng-show="d === 0">Not Available</span>
  </li>
</ul>

The data can be passed through a function to pull all the 0 after the first one:

  $scope.data = [1,2,3,0,1,0,0,1,0,2]
  $scope.pullDupes = function(array) {
    var newArray = [];
    var zero;
    for(var i = 0; i < array.length; i++) {
      if (array[i] !== 0) {
        newArray.push(array[i])
      }
      if (array[i] === 0 && !zero) {
        zero = true;
        newArray.push(array[i])
      } 
    }
    return newArray;
  }
  $scope.newData = $scope.pullDupes($scope.data);

Plunker

like image 186
tpie Avatar answered Oct 22 '22 03:10

tpie


You can show only the first message see here :

<div ng-repeat="item in list | orderBy: 'cost'">
    <div style="color:red" ng-show="item.cost == 0 && $first">Message Goes Here</div>
    <hr>
    <div>{{item.name}} - Price : {{item.cost}}</div>
</div>

and here is a plunker for it :

http://plnkr.co/edit/RwZPZp9rFIChWxqF71O7?p=preview

also the ng-if you are using it wrong you need to do it like this item.cost for the next time

Cheers !

like image 34
Moe Shaaban Avatar answered Oct 22 '22 01:10

Moe Shaaban


Here is the best way I could find to get it done.

Markup

<div class="sold-out-message" ng-if="displaySoldOutMessage(item)">Sorry, sold out</div>

Controller

$scope.firstSoldOutItemId = false;
$scope.displaySoldOutMessage = function(item) {
   if ( item.cost ) return false;

   $scope.firstSoldOutItemId = $scope.firstSoldOutItemId || item.id;

   return item.id == $scope.firstSoldOutItemId;
};
like image 38
matthewdaniel Avatar answered Oct 22 '22 03:10

matthewdaniel