Basilin Joe
Basilin Joe

Reputation: 702

How to prevent angular filter triggering in each digest?

I am working on an angular application,in which i have to use 20 different filters,i planned to filter data at client side, i.e using custom angular filters,i have created all custom filters,but the problem is every time a value is changed by some functions my filters triggers and its becoming a mess now.Is there a way to prevent this from happening ?

Upvotes: 2

Views: 817

Answers (2)

justGoscha
justGoscha

Reputation: 24135

EDIT

Actually a better solution is to use the one-time binding provided by Angular 1.3+ which has the syntax {{::expression}}


Old answer

One solution is probably the bindonce directive https://github.com/Pasvaz/bindonce

Instead of ng-bind you use bo-bind to bind values and they only get evaluated once and no watches get applied to them so they don't have to evaluate again. Therefore filters applied are also only executed once.

Here a link to the filter section: https://github.com/Pasvaz/bindonce#filters

It is really performant if you have to make many bindings per page. Angular can get pretty slow if you have 100s or 1000s of bindings on one page.

Upvotes: 0

Renan Ferreira
Renan Ferreira

Reputation: 2150

You can always inject the $filter service in your controller and use it to filter the data before the binding of the new value. Something like this:

https://jsfiddle.net/relferreira/4r37kzu8/

HTML

<div data-ng-app="app">

  <div data-ng-controller="MainController as main">
    {{main.test}}
    {{main.testFilter}}
  </div>

</div>

JS

angular.module('app', []);

angular.module('app')
    .controller('MainController', mainController);

mainController.$inject = ['$scope', '$filter'];

function mainController($scope, $filter){

    var vm = this;

    vm.test = 'test filter: '
    vm.testFilter = $filter('date')(new Date('2015-12-02'));
}

The inclusion of one-way data binding may help to. Just use the syntax {{:___}} in your HTML

Upvotes: 1

Related Questions