R
R
Rrooom2014-08-20 09:58:24
JavaScript
Rrooom, 2014-08-20 09:58:24

How to preload models for AngularJS?

There is such a thing for Backbone - backbonejs.ru/#FAQ-bootstrap
And what is the right way to do it for angular?
There is an ngInit directive, but it was not particularly recommended on stackoverflow, they say it is not accepted. Yes, and it doesn’t come out very beautifully, the syntax is inconvenient.

Answer the question

In order to leave comments, you need to log in

2 answer(s)
S
Sergey, 2014-08-20
@Rrooom

What about the ng-init directive? In your example, there is no such thing at all.
The data should not be stored in the template, that is, in the attributes in the form of text, so that you would then have to parse it manually. If you carefully look at what will be the output of the example you have given, you will see the following:
Let's say our collection will look like
then the user will receive the following html stuff:

<script>
  var accounts = new Backbone.Collection;
  accounts.reset([{id: 1, username: 'foo'}, {id: 2, username: 'bar'}]);
</script>

hence no backbone does any parsing by hand.
What can be done in angular. You can declare a constant module that the main application will use. If you modify your example, it will look like this:
<script>
angular.module('prefetchedData', [])
    .constant('users', <%= @accounts.to_json %>)
    .constant('projects', <%= @projects.to_json(:collaborators => true) %>);
</script>

In the main application, you can already inject this data wherever you need. and process at the same initialization. This method has its drawbacks, in particular, your application starts to depend on some prefetchedData module, but on the other hand, we get rid of the need to make this data global, which is even better than in the case of the backbone, where it was necessary to sculpt a crutch for this, and again you can resolve this data directly in services, which is just as convenient.

K
kompi, 2014-08-20
@kompi

Alternatively, initialize data via injector()

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question