Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

AngularJS - Bootstrapping data into a service on page load

In an angularjs app, I am attempting to use a custom service to hold the app's main data, "items". However, I would like to bootstrap the data into the service upon the initial page load, in order to avoid a separate ajax request to the server to get it. What would be cleanest way to go about doing this?

Here is a snippet of my service for reference:

app.factory('items', function() {
    var itemsService = {},
        items = [];

    itemsService.list = function() {
        return items;
    };

    itemsService.add = function() {
        /* ... */
    };

    return itemsService;
});

And on the backend I am using node.js + expressjs + jade, so I would be injecting the data into the page using:

!{JSON.stringify(items)}
like image 441
Bill Dami Avatar asked Oct 04 '22 16:10

Bill Dami


1 Answers

Put your bootstrapped data from the server into a global JavaScript variable. Have your service assign items to that global variable (or copy the data into items).

like image 91
Mark Rajcok Avatar answered Oct 20 '22 09:10

Mark Rajcok