Search code examples
javascriptangularjsangular-filters

Assign filtered data to controller variable in ng-if


I want to assign filtered data to controller variable in ng-if:

<section ng-if="($ctrl.filteredOperations = $ctrl.operations | filter: customFilter).length > 0">
    <header>Count: {{$ctrl.filteredOperations .length}}</header>
    <div ng-repeat="operation in $ctrl.filteredOperations ">...</div>
</section>

I tried different approaches with no luck.

UPDATE

Why am I doing this?

I have a service which holds the collection of operations.

financialService.operations(); - this returns operations, from API or from cache.

So in my controller:

financialService.operations().then(function(ops){
    vm.operations = ops;
});

Now if I update my cache by any means, it'll update my view.


Solution

  • I would suggest you to move the filtering to your controller:

    $ctrl.filteredOperations = $filter('customFilter')($ctrl.operations);
    

    And then display it as the following:

    <section ng-if="$ctrl.filteredOperations.length">
        <header>Count: {{$ctrl.filteredOperations.length}}</header>
        <div ng-repeat="operation in $ctrl.filteredOperations">...</div>
    </section>
    

    In my opinion, when the logic become complex, it is always better to move it to controller instead of doing all in HTML.