Marc
Marc

Reputation: 1043

Angularjs: set accessible service across multiple controllers

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?

Upvotes: 0

Views: 51

Answers (1)

Ero
Ero

Reputation: 520

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;
    }
}

Upvotes: 1

Related Questions