Travis Heeter Travis Heeter - 7 months ago 51
AngularJS Question

How to use a model in a filter?

I need to pass bunch of variables to a filter, so I figured it'd be easier to pass the whole model, since it's just a reference anyway. So I tried to do this (this is a simplified version):

app.filter('applyLimit', function() {
return function(files, m) {
v.analyze = i < m.limit
return v

angular.module("app").component("h2jcomponent", {
templateUrl: "html/View.html",
controllerAs: "m",
controller: ['$filter', H2J_Controller]

function H2J_Controller($filter) {
var m = this
m.limit = 1
var files = [{name:'',analyze:true},{name:'',analyze:true}]

However I'm getting the following error:

TypeError: Cannot read property 'limit' of undefined

I'm assuming this is because I can't pass my entire model to a filter, but I'm not sure. Is this possible?


first filter's argument should be processed array (files in our case) and then after it any optional additional arguments (limit in our case). This way, our filter may be used in HTML with directives like ng-repeat (ng-repeat="file in vm.files | vm.applyLimit : vm") or just angular expression within curly braces like

<pre>{{ vm.files2 | applyLimit : vm | json }}</pre>

so I rewrote filter to:

app.filter('applyLimit', function() {
  return function(files, scope) {
    return, i){
      v.analyze = i < scope.limit;
      return v;

updated plunker: