Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Angular docs: how can one share stateless/stateful code between controllers?

Tags:

angularjs

Been reading the Angular.js' Controller docs and stumbled across:

Sharing stateless or stateful code across Controllers — Use angular services instead.

But this leaves me uncertain. How do one can share a stateless/stateful code between controllers? Or what does the "code" mean here? A model? Besides, controllers do not refer to each other, as far as I understood. Can anyone clear things out for me(others) please? Thanks.

like image 491
Aleksandr Makov Avatar asked Nov 22 '13 12:11

Aleksandr Makov


Video Answer


1 Answers

I think what they are referring to might be one of the methods to "persist" data, sharing it between controllers or between route-changes. One way to do that is to put it in your rootScope, another is to use a service. If you define a service like this:

.factory("MyDataObject", function() {
    return {};
})

Then MyDataObject will be the same object anywhere you call it, allowing you to save things into it in order to share data, functions and states between controllers (or directives, or other services, etc).

You never know with the Angular documentation, but I would guess that is what they are talking about :)

See for example this answer: Angularjs, passing scope between routes

like image 171
Erik Honn Avatar answered Oct 13 '22 08:10

Erik Honn