CountGradsky CountGradsky - 1 year ago 45
AngularJS Question

Angular directive that checks for number of children li elements

So I have a simple ul that ng-repeats li elements from the external source gathered with a promise. I also have a search input that filters these elements, and I would like for the ul to hide when it contains no more elements that satisfy the search.

I made this directive, but its not working:

.directive('predictive', function() {
return {
restrict: 'A',
link: function(scope, element) {
if (!$(element).children("li").length) {

But the directive hides everything because it applies too fast, before the service that gets the data fills the list with li's.

Anything I can do about it?

EDIT: the markup

<input type="text" ng-model="predictiveSearch"></input>

<ul ng-repeat="(key, option) in Service1.predictive" predictive>
<li ng-repeat="option in option | filter:predictiveSearch">
<a href="" ng-click="handlePredictiveSelection(option)">{{option}}</a>

Answer Source

You can use the filter alias of ng-repeat and check that length in an ng-if

<ul ng-repeat="(key, option) in Service1.predictive" ng-if="filteredArray.length">

        <li ng-repeat="option in option | filter:predictiveSearch as filteredArray">