Angular js - 如果ng-repeat为空,则显示消息

use*_*955 27 javascript angularjs

以下AngularJS应用程序正在使用ng-repeat和应用过滤器.某个应用的过滤器不会留下任何值.如何显示通知?

小提琴

HTML

<div >
<div data-ng-controller="myCtrl">


    <ul >
        <li data-ng-repeat="item in values | filter:filterIds()"> 
            <code>#{{item.id}}</code> Item
        </li>
    </ul>

    <p ng-show="!values.length">no vals with this filter</p>
    <button ng-click="loadNewFilter()"> filter now</button>
</div>


</div>
Run Code Online (Sandbox Code Playgroud)

AngularJS

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

app.controller('myCtrl', function ($scope) {
$scope.values = [{
    id: 1
}, ....
}];

$scope.filter = [1,2,3,4,5,6];

$scope.filterIds = function (ids) {
        return function (item) {
            var filter = $scope.filter;

                 return filter.indexOf(item.id) !== -1;         
        }
 }

$scope.loadNewFilter = function (){
    $scope.filter = [-1];
    $scope.$apply();
}

});
Run Code Online (Sandbox Code Playgroud)

Raj*_*amy 39

我想这就是你想要的:

var app = angular.module('myApp', []);    
app.controller('myCtrl', function ($scope) {
  $scope.values = [
    {id: 1}, 
    {id: 2}, 
    {id: 3}, 
    {id: 4}, 
    {id: 5}, 
    {id: 6}];
    
  $scope.filter = [1,2,3,4,5,6];
        
  $scope.filterIds = function (ids) {
    return function (item) {
      var filter = $scope.filter; 
      return filter.indexOf(item.id) !== -1;       	
    }
  }
        
  $scope.loadNewFilter = function (){
    $scope.filter = [1,5];    
  }                 
});
Run Code Online (Sandbox Code Playgroud)
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<div ng-app="myApp">
  <div data-ng-controller="myCtrl">               
    <ul>
      <li data-ng-repeat="item in testValue=(values | filter:filterIds())"> 
        <code>#{{item.id}}</code> Item
      </li>
    </ul>           
    <p ng-show="!testValue.length">no vals with this filter</p>
    <button ng-click="loadNewFilter()"> filter now</button>
  </div>
</div>
Run Code Online (Sandbox Code Playgroud)

FIDDLE LINK

这是另一个FIDDLE LINK检查这个


dfs*_*fsq 27

我会采用非常简单的CSS方法:

HTML:

<ul>
    <li data-ng-repeat="item in values | filter:filterIds()"> <code>#{{item.id}}</code> Item</li>
    <li class="no-items">There are no matching items.</li>
</ul>
Run Code Online (Sandbox Code Playgroud)

CSS:

li + .no-items {
    display: none;
}
Run Code Online (Sandbox Code Playgroud)

所以基本上li.no-items只有在没有其他LI人的情况下才可见,否则就是隐藏的.我认为这比性能更好,而不是再引入一个观察者ngShow/ngHide.

演示:http://jsfiddle.net/z9daLbLm/5/


Vam*_*msi 8

这是一个工作示例:http://jsfiddle.net/z9daLbLm/2/

您可以保存过滤器的结果 ng-repeat

<div ng-repeat="item in filteredValues = (values | filter:filterIds())">{{item}}</div>
Run Code Online (Sandbox Code Playgroud)

结果存储在filteredValues 然后在DOM中使用此过滤值

<div ng-show="!filteredValues.length">No Items</div>
Run Code Online (Sandbox Code Playgroud)