When my app loads i register a filter and a service with angular.
But the filter is trying to execute before the service comes back with the data so my items collection is barking in the filter.
I had a fiddle for it but i don’t know if you can use $http in a fiddle because it is an external resource. Here is what i have Fiddle
Sorry that it doesn’t actually work. its been through alot.
I think my issue is timing. I need the filter to wait for the http response or just not ‘enforce’ itself.
The error i get now is ‘items is undefined’ cause that is where the filter is being applied.
I did have this working before i tried to mash the http call into a service. But i feel like that is the angular way and i “just want to be in compliance”.
When my controller fires it makes the call to fetch data:
eventApi.async().then(function () {
$scope.eventCollection = eventApi.data();
});
but before it gets back the filter is applied in the html:
<tr ng:repeat="event in events | myEventFilter:ddlFilter |
orderBy:sort.column:sort.descending">
Here’s a fork of your updated fiddle that fixes a couple missed dependencies (
eventApinot injected into the controller,$timeoutnot injected into theeventApiservice). My comments will be based on this code: http://jsfiddle.net/BinaryMuse/zww7e/1/This fiddle successfully gets us to the issue you posted about: “Cannot read property ‘length’ of undefined” in your filter. In general, filters should be able to handle null/undefined values by default. I would simply modify the filter to read something like this:
That should take care of your root problem; the fiddle now runs without errors, although it doesn’t appear to work properly; as far as I can tell, it’s because you’re setting
$scope.eventCollectioninstead of$scope.eventsin theif (live)section of your controller. Making this change causes data to actually show up in the view.However, you may be interested in another property of Angular: when you use a promise built with
$q, you can bind the view directly to the promise, and the view will treat it as though you bound it to the resolved value of the promise. So, for example, you can do the following:Here’s an updated version of the fiddle that demonstrates this technique: http://jsfiddle.net/BinaryMuse/zww7e/2/
[Update]
As pointed out by Jeff in the comments, Angular is deprecating automatic promise unwrapping; you can see the commit here, but here is the message: