Question

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)}
Was it helpful?

Solution

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).

OTHER TIPS

How about something like this:

app.run(['items', function (items) {
   items.load();
}])

This presumes your items service has a load function (or something like it) that does the actual Ajax work using either $http or $resource.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top