5

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)}
1

2 Answers 2

3

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

Sign up to request clarification or add additional context in comments.

3 Comments

that was what i was thinking, but where should that assignment/copy occur within my code? Because simply doing it within the app.factory call to create the service, replacing items = [] with items = window.bootstrappedData (where bootstrappedData is the global javascript variable) does not seem to work.
I would put the assignment/copy where you tried. The only thing I can think to check is to make sure the JavaScript code that assigns the data to global variable bootstrappedData is executing before Angular.
turns out was just a small error on my part, the script tag I placed the data into had its type attribute set to js/data so it was not being executed as javascript. >_<
1

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.

2 Comments

but then if I am just calling my load() function, I am still just making that ajax request to load the data instead of using the inline javascript injected array of items, or am i totally misunderstanding your answer?
I am assuming that a "load" function would perform an Ajax request whose success function would assign the new data set into the inline "items" variable. So "load" doesn't return anything; its only purpose is to get data into your internal "items" array.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.