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)}
有帮助吗?

解决方案

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

其他提示

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.

许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top