Travis Heeter Travis Heeter - 1 month ago 20
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) {
return files.map(function(v,i){
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:'foo.java',analyze:true},{name:'bar.java',analyze:true}]
$filter('applyLimit')(files,m)
}


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?

Answer

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 files.map(function(v, i){
      v.analyze = i < scope.limit;
      return v;
    })
  }
});

updated plunker: https://plnkr.co/edit/0TYC56eNLSugPp8tDFeH?p=preview