Share Data in AngularJs

2019-02-27 22:10发布

问题:

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

回答1:

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 and Services. 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:

<script src="https://rawgithub.com/gsklee/ngStorage/master/ngStorage.js"></script>    

Then in your module definition, inject the ngStorage:

var sampleApp = angular.module('Your App Name', ['ngStorage']);  

And , in your controllers:

sampleApp.controller('PhoneListCtrl', 
['$scope', '$http', '$sessionStorage',
function($scope, $http,$sessionStorage) {
    $http.get('App_Data/phonelist.json').
        success(function(returnDataFrmJson){
            $scope.phonesScope = returnDataFrmJson;
            $sessionStorage.sharedValue = returnDataFrmJson;//keeping the value in session
        });
}]);    

controller that will access the shared data of the first one

sampleApp.controller('AddIPhoneController', 
['$scope', '$http','$sessionStorage',
function($scope, $http,$sessionStorage) { 
    $scope.newInput= 'sample text';

    $scope.sharedText= $sessionStorage.sharedValue;
}]);

Then in your View:

{{newInput}}{{sharedText}}


回答2:

If I understand your question correctly you could create a service and inject it to other controllers like so:

    sampleApp.service('sharedProperties', function() {
        var sharedText = '';
        return {
            getSharedText: function() {
                return sharedText;
            },
            setSharedText: function(newText) {
                sharedText = newText;
            }
        }
    }

And then in your controller:

    sampleApp.controller('ControllerName', ['sharedProperties', function(sharedPropertied) {
        var text = sharedProperties.getSharedText();
    }]);

Obviously you should set the text somewhere by injecting the service and setting it in another controller.



回答3:

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



回答4:

You are doing wrong the data you want to share between controllers should exist in service not controller

Service :

 sampleApp.service("MyService",function($http){
       this.phoneList = function(){
             return $http.get('App_Data/phonelist.json');
       };         
 });

Controller 1 :

  sampleApp.controller('PhoneListCtrl1',function($scope,MyService) {
        MyService.phoneList()
           .then(function(list){
                 $scope.phoneList = list;
            });
    });

Controller 2 :

 sampleApp.controller('PhoneListCtrl2',function($scope,MyService) {
            MyService.phoneList()
               .then(function(list){
                     $scope.phoneList = list;
                });
    });


回答5:

Try $rootScope.phonesScope. This may help. understand rootscope



回答6:

It depends on the requirements:

  1. If your purpose is to share the data among controllers without notifying the controllers when the data is populated/updated, go with the service/factory approach.
  2. If you also want to notify the other controllers while populating/updating the data then you can make use of angular events($broadcast/$emit).
  3. And if you want to preserve the data on page refresh or browser close, you can opt for session/local storage.