Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using $filter in Angular directive

I have built out an Angular directive to display a D3 visualization. I make use of $filter within the tickFormat function on my y-axis like so:

ySalesAxis = d3.svg.axis()
  .orient('left')
  .ticks(6)
  .scale(ySalesScale)
  .tickFormat(function(d) {
    return $filter('formatSalesValue')(d.value, 'USD');
  });

The problem I'm seeing is that none of these tick labels appear when the page first loads. Indeed if I console.log($filter('formatSalesValue')(d.value, 'USD')) I get 6 undefined (since my ticks property is set to 6). However, as soon as I take an action, clicking within the brush filter for example, the tick labels appear properly formatted.

enter image description here

My formatSalesValue filter calls a service (async operation) because there are dozens of currencies cycling into and out of the system, details of which I retrieve from a DB. I am sure this is the reason my tick labels are undefined. What can I do to make sure these values appear right after page load? Note: I've attempted wrapping my tickFormat function in a call to scope.$apply but I get a digest already in progress error.

like image 254
MattDionis Avatar asked Feb 29 '16 21:02

MattDionis


People also ask

What is $filter in AngularJS?

Overview. Filters are used for formatting data displayed to the user. They can be used in view templates, controllers or services. AngularJS comes with a collection of built-in filters, but it is easy to define your own as well.

What is the correct way to apply multiple filter in AngularJS?

7) Which of the following syntax is correct for applying multiple filters in AngularJS? Answer: A is the correct option. The syntax of applying multiple filters in AngularJS can be written as: {{ expression | filter1 | filter2 | ... }}

How does filter work in angular?

The “filter” Filter in AngularJS is used to filter the array and object elements and return the filtered items. In other words, this filter selects a subset (a smaller array containing elements that meet the filter criteria) of an array from the original array.


1 Answers

Axis's tickFormat method runs passed callback and uses value returned by it in sync way. That's why you get undefined on the first call, as your $filter is async.

If this async call is only for performance reasons you should make it sync and look for improvements elsewhere. Should angular watch for so many independent changes it could clog with $digest cycles.

If you make JSBin I probably could tell you more.

like image 189
m1gu3l Avatar answered Oct 11 '22 19:10

m1gu3l