Adrian Gunawan Adrian Gunawan - 5 months ago 20
AngularJS Question

AngularJS - placeholder for empty result from filter

I want to have a place holder, e.g.

<No result>
when filter result returns empty. Could anyone please help? I don't even know where to start...

HTML:

<div ng-controller="Ctrl">
<h1>My Foo</h1>
<ul>
<li ng-repeat="foo in foos">
<a href="#" ng-click="setBarFilter(foo.name)">{{foo.name}}</a>
</li>
</ul>
<br />
<h1>My Bar</h1>
<ul>
<li ng-repeat="bar in bars | filter:barFilter">{{bar.name}}</li>
</ul>

</div>


JS:

function Ctrl($scope) {

$scope.foos = [{
name: 'Foo 1'
},{
name: 'Foo 2'
},{
name: 'Foo 3'
}];

$scope.bars = [{
name: 'Bar 1',
foo: 'Foo 1'
},{
name: 'Bar 2',
foo: 'Foo 2'
}];

$scope.setBarFilter = function(foo_name) {
$scope.barFilter = {};
$scope.barFilter.foo = foo_name;
}
}


jsFiddle: http://jsfiddle.net/adrn/PEumV/1/

Thanks!

Answer

A tweak on the approach that only requires you to specify the filter once:

  <li ng-repeat="bar in filteredBars = (bars | filter:barFilter)">{{bar.name}}</li>
</ul>
<p ng-hide="filteredBars.length">Nothing here!</p>

Fiddle