Sherlock
Sherlock

Reputation: 5627

Hide if there is no data in angular

<table>
    <tr ng-repeat="(key, values) in myData">
        <td> {{ key}} </td>
        <td>
            <div ng-repeat="item in values| limitTo:limit | filter: {source: sourceFilter}" ng-include="'templates/item.html'"/>
        </td>
    </tr>
</table>

With the above code I looping through the keys/values, where key is a string and value is an array. I am filtering the values by the 'source' property - this means that sometimes some keys have no items displayed. I would like to hide all of the rows that do not have any items.

I have tried using custom filters, and ng-show/ng-hide, but as I am an angular noob I can't seem to figure out how to do this. Could someone show me an example of how I can achieve this ? Many thanks.

Upvotes: 0

Views: 4821

Answers (3)

Nellas
Nellas

Reputation: 11

I usually make a directive that handles this case, that way I can use it more than once and I am not repeating code. Something like:

.directive('nodata', [function () {
    return {
        restrict: 'A',
        link: function (scope, element, attr) {
            window.setTimeout(function () {
                if (element[0].innerText === '') {
                    element[0].innerText = '–';
                    element.css({
                        # use css here to display none or change color etc
                        # at your preference   
                    });
                }
            }, 0);
        }
    };
}])

Then you can just add nodata>{{ yourAngular.binding }} to your html element.

Upvotes: 1

Maxim Shoustin
Maxim Shoustin

Reputation: 77930

Try:

<table>
    <tr ng-repeat="(key, values) in myData" 
        ng-hide="(values | filter: {source: sourceFilter).length == 0">
        <td> {{ key}} </td>
        <td>
            <div ng-repeat="item in values| limitTo:limit | filter: {source: sourceFilter}" ng-include="'templates/item.html'"/>
        </td>
    </tr>
</table>

Some example in Plunker

Upvotes: 1

tymeJV
tymeJV

Reputation: 104795

You can do something like this:

<tr ng-repeat="(key, values) in myData" ng-hide="itemValues.length == 0">
    <td> {{ key}} </td>
    <td>
        <div ng-repeat="item in values = (itemValues | limitTo:limit | filter: {source: sourceFilter})" ng-include="'templates/item.html'"/>
    </td>
</tr>

Upvotes: 2

Related Questions