How to Share data to all controller?
I have a controller that pull data from server(file.json) that i want to share to other controller
sampleApp.controller('PhoneListCtrl',
['$scope', '$http',
function($scope, $http) {
$http.get('App_Data/phonelist.json').
success(function(returnDataFrmJson){
$scope.phonesScope = returnDataFrmJson;
});
}]);
controller that will access the shared data of the first one
sampleApp.controller('AddIPhoneController',
['$scope', '$http',
function($scope, $http) {
$scope.newInput= 'sample text';
$scope.sharedText= dataFromSharedControll;
}]);
the html file that will show the data.
{{newInput}} {{sharedText}}
You are doing wrong the data you want to share between controllers should exist in service not controller
Service :
Controller 1 :
Controller 2 :
If I understand your question correctly you could create a service and inject it to other controllers like so:
And then in your controller:
Obviously you should set the text somewhere by injecting the service and setting it in another controller.
You should share data via a service. Also the $http calls in the controller should be moved to a service. If you then inject the service in the controller, you can call the methods/data from that service in the controller.
I suggest you take a look at John Papa's style guide found here: https://github.com/angular/angular
It depends on the requirements:
Well, there are various options for you like using:
$sessionStorage
,localStorage
,appConstant
,$localStorage
and so on.You can even share the data between controllers using
Factory
andServices
. I will be giving you a simple example of using$sessionStorage.
In order to use
$sessionStorage
or$localStorage
, you need to inject ngStorage.First in your index.html, include the source:
Then in your module definition, inject the ngStorage:
And , in your
controllers
:controller
that will access the shared data of the first oneThen in your
View
:Try
$rootScope.phonesScope
. This may help. understand rootscope