scferg5
scferg5

Reputation: 2013

Unique AngularFire calls in Angular template functions

I'm using AngularFire and have an ng-repeat list with items that contain data specific to the "author" of that item (multiple users can add to the list), such as name, location, etc. I'm not writing that data into the array being iterated over by ng-repeat since it could change in the future. Instead, that author-specific data is store in a different location so the goal is that if the author changes their information, all of it is reflected in the list.

For a contrived example, imagine I'm iterating over a list of books from different authors. That list will contain the book-specific data (such as title, publish date, etc.) but I will also want to display the author's information in the list. Instead of including the author's information directly within the book data, I want to simply reference that author ID, and pull in whatever data is in their profile so if they change their name, it'll reflect the changes in all of their book listings.

That means I'm left to make async calls to Firebase to retrieve that information for each list item via a template function, such as {{getAuthorName(authorId)}}. The only problem is that they're async calls and the template function evaluates before the data is available.

I've looked into how to accomplish but have yet to find a solution that accommodates what I need. The answers here seem close, but they appear to no longer work in Angular >= 1.2.0 and they don't account for having to return different data for each template function call.

Update

Here is a JSFiddle with what I have now. I've made some progress, but all that's being returned now is the promise object as expected. I'm not sure how to implement .then in this scenario to get the actual value.

Any help would be great.

Upvotes: 1

Views: 89

Answers (1)

Mathew Berg
Mathew Berg

Reputation: 28750

You can make use of $firebaseObject and then store that in an object to make sure it doesn't get hit again. like so:

var authors = {};

$scope.getAuthorName = function(authorId){
    if(!authors[authorId]){
        var authorRef = new Firebase(fburl + "/authors/" + authorId);            
         authors[authorId] = $firebaseObject(authorRef);
    }
    return authors[authorId];
};

You can see the working fiddle here: http://jsfiddle.net/0rcdpq47/

Upvotes: 2

Related Questions