0

I have a navbar controller where I have a search bar that searches books. In my navbar ui-router state, I resolve the books and set it within a Books service. As a result, I can then access all the books. This is not just in the navbar, but across all controllers from that point forward.

However, in my summary dashboard, I want to list all the books I've pulled. Instead of redoing a call to pull the books, I want to use the Books service. If I start the app at the summary dashboard, I am running into problems because the summary dashboard doesn't know how to wait for the Books service to be populated from the navbar.

My question is how do I make the summary dashboard wait for the navbar controller to resolve the Books service?

Marc
  • 1,033
  • 2
  • 10
  • 28

1 Answers1

1

your navbar can broadcast an event and your summary dashboard can wait for it.

navbar controller

$scope.$broadcast('booksLoaded', books);

summary dashboard controller

$scope.$on('booksLoaded', function(event, books) {
    $scope.books = books;
});

another option is to use a service to temporarily store the data.

angular.module('app').factory('BooksService', BooksService);

function BooksService() {
    return {
        getBooks: getBooks,
        setBooks: setBooks
    };

    var _books = [];

    function getBooks() {
        return _books;
    }

    function setBooks(books) {
       _books = books;
    }
}
Ero
  • 491
  • 1
  • 3
  • 15
  • @Marc if my answer worked, please make this the accepted answer – Ero Jul 14 '17 at 19:24
  • I understand your answer, but now looking into how to apply it. The problem is that I'm trying to broadcast to a service. It looks like that is frowned upon since service's aren't really part of the scope. It seems repetitive to store the navbar info in the service, but then get the summary books off the broadcast (rather than the service). Essentially, I'm trying to have navbar (get books) -> book service (store books) -> summary (get books from service) – Marc Jul 14 '17 at 20:21
  • why would you broadcast to the service? Personally I would recommend pulling the books list from your backend....anyways you could also do this: save the books to books service in the navbar when they load, then broadcast the event 'booksLoaded', then in your summary dashboard listen for that event and load the books from the service instead of passing them through the broadcast – Ero Jul 15 '17 at 15:17