JSAddict
JSAddict

Reputation: 12427

Is there any way to get data from controller to filter?

I am new to angularjs.

I want to use the data in filter which i have in my controller.

Is there any specific way to do dat?

Upvotes: 1

Views: 110

Answers (2)

JSAddict
JSAddict

Reputation: 12427

in controller

$scope.variable=['1','2','3'];

in view

<span>{{ variable | f1 }}

in filter

angular.module('Filters', ['Services']).filter('f1', function() {
 var events=Events.query();
 return function(input) { 
 alert(input)->['1','2','3']
}; });

Upvotes: 3

Caio Cunha
Caio Cunha

Reputation: 23394

The best way is to pass the data as an additional parameter: <span>{{ value | filter:anotherValue }}</span>. This way, the value and anotherValue are controller's scope variables. The filter is your custom filter. The filter will receive the anotherValuecontent as the second parameter, and a change to it will reapply the filter. Here is a fiddle.

Another solution, if you it's not proper to pass the information along all times you write the filter, is to use a shared service between them. You can then expose the properties from the controller and use in the filter. Another fiddle here (just change the input text value).

Basically, this is what happens on the fiddle:

// sets the shared data
mod.controller('Ctlr', function(sharedService) {
  sharedService.data = 'something';
}

// uses the shared data
mod.filter('customFilter', function(sharedService) {
  return function(input) {
     return input + sharedService.data;
  };
});

// the shared service that holds the data
mod.service('sharedService', function(){ 
  this.data = 'default value';
});

Upvotes: 2

Related Questions