Atanas Palavrov Atanas Palavrov - 5 months ago 88
AngularJS Question

How to avoid ng-init in angular?

I want to show message when ng-repeat collection is empty i.e.:

<div ng-init="filteredArray=(array|filter:{...})">
<h1 ng-if="!filteredArray.length">Empty array</h1>
<table ng-if="filteredArray.length">
<tr ng-repeat="element in filteredArray">
<td>{{element}}</td>
</tr>
</table>
</div>


The problem is that ng-init will not watch for modification of the source array. Any hint how to do it properly?

Answer

You can just create the filtered variable in the ng-repeat, and use that one:

<div>
    <h1 ng-if="!filteredArray.length">Empty array</h1>
    <table ng-if="filteredArray.length">
        <!-- here angular assigns the filtered array to the 'filteredArray' variable, 
        which then can be used -->
        <tr ng-repeat="element in filteredArray=(array|filter:{...})">
            <td>{{element}}</td>
        </tr>
    </table>
</div>

See also this jsfiddle


EDIT

If you don't like the ugly expression, you can also do something like this:

function myController ($scope, $filter) {
    $scope.$watch("theFilter", function (val) {
        $scope.filteredArray = $filter("filter")($scope.array, val);
    });
}

And in your html:

<tr ng-repeat="element in filteredArray">
    ..
</tr>