Skip to content

Instantly share code, notes, and snippets.

@katowulf
Last active November 7, 2019 21:10
Show Gist options
  • Save katowulf/bee266e31aa60cb0eed6 to your computer and use it in GitHub Desktop.
Save katowulf/bee266e31aa60cb0eed6 to your computer and use it in GitHub Desktop.
Filter records loaded into AngularFire based on some criteria.
// this will be much more efficient than $watch()
app.factory('FilteredArray', function($firebaseArray) {
function FilteredArray(ref, filterFn) {
this.filterFn = filterFn;
return $firebaseArray.call(this, ref);
}
FilteredArray.prototype.$$added = function(snap) {
var rec = $firebaseArray.prototype.$$added.call(this, snap);
if( !this.filterFn || this.filterFn(rec) ) {
return rec;
}
};
return $firebaseArray.$extend(FilteredArray);
});
app.controller('...', function($scope, FilteredArray) {
var ref = new Firebase('https://kato-books.firebaseio.com/');
$scope.data = FilteredArray(ref, function(rec) {
return rec.author !== 'Stephen King';
})
});
@GreggSetzer
Copy link

katowulf,
Thank you for posting this example. I am having difficulty getting the example to detect the function that is passed in as the second argument into FilterArray(). I have created a plunker. When you have a moment, will you please review the plunker and provide your thoughts on how to get it to work.

Thank you.
Gregg
http://plnkr.co/edit/FpKPbh6vr8R9dFIgzkIq

@katowulf
Copy link
Author

Looks like the example was slightly confused. Added the constructor method.

@AdrienDC
Copy link

Hi @katowulf,
thanks for this, it is really helpful for my project ! Just a concern, do you know if it's possible to make the applied filter dynamic?
I explain, I'm displaying a list of user based on few filters but if for one using the value for which I'm filtering is changing, I would like the list to be updated real time. Like for your example, imagine you change the author name while you have already displayed the result.

@rainabba
Copy link

At Line 4 ( https://gist.github.com/katowulf/bee266e31aa60cb0eed6#file-filter_using_extend-js-L4 ), 'this' is undefined so I get a TypeError at that point. What should the scope be there? Have I missed something in this very straight-forward implementation?

@emil-alexandrescu
Copy link

@rainabba You should initialize array with new FilteredArray(...).

@douwevdijk
Copy link

I know it is are a couple of years later :). but how can this be used in combination with updates / removals?

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment