Making a variable accessible across controllers and models


#1

As soon as my app launches, I send a GET request to an API to get stuff and display it on screen. This code lives in my controller and it’s really short… a couple of lines. Now, I need that same stuff to be accessible from a service (another service, not the one linked to that controller). What is the best way to do this?
Should I do
$rootScope.name = 'Jules';
?
Or is there a better way?


#2

never use the rootScope for that.

create a service or factory for sharing data, sending http-requests.

Services/factories/providers are singletons in angularjs! So if you need to share values across multiple controllers use them!


#3

Do you mean: Creating a service that sends HTTP requests to other services within the same app? Wouldn’t that be a waste of traffic? I am not sure if I understood you correctly but, either way, would you mind jotting down a super-minimal example of that? I am quite new to Ionic! Still trying to learn the basics :slight_smile:


#4

If it’s a simple variable, why not creating it outside angular?

Something like…

var Foo = 'bar';
var myApp = angular.module(...)

#5

You could also use a constant.
myApp.constant('apiUrl', 'http://myApiEndPoint.com/');