How to show an element once in ng-repeat

I need to scroll through the list by price, and as soon as the price is not there, I will show a message with the inaccessible, but I do not want to show it for each empty element. I am 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> 
+6
source share
4 answers

Here is the best way I could find to do this.

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; }; 
+1
source

You can conditionally display two spans - one if it is 0 (your message is "unavailable"), and the other for something 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> 

Data can be passed through a function to pull all 0 after the first:

  $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

+2
source

You can show only the first message:

 <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 him:

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

also ng-if you use it incorrectly, you need to do it as item.cost next time

Greetings!

+1
source

You can try using $ scope. $ whatch with a boolean variable:

  <div ng-model="actualItem" ng-repeat="item in list | orderBy: 'cost'"> <div ng-if="cost == 0 && oneMessage == true">Sorry the following are unavailable</div> <div>...my item here...</div> <div> </div> 

And in your controller you look at the actual one:

  $scope.oneMessage = false; var cpt = 0; // if 1 so you stop to send message $scope.$watch('actualItem',function(value){ if(value.cost == 0 && $scope.oneMessage == false && cpt < 1) // i don't know what is your cost but value is your actual item { $scope.oneMessage = true; cpt++; } else if($scope.oneMessage == true) { $scope.oneMessage == false; } }); 

I'm not sure about this, but you can try. This, of course, is not the best way.

0
source

Source: https://habr.com/ru/post/987067/


All Articles