pass data between controllers in AngularJS dynamically [duplicate]

本小妞迷上赌 提交于 2020-12-16 07:18:25

问题


i have tow controller in angularjs. if one controller change data other controller display updated data. in fact first controller has a event that it occur second controller display it. for this propose i wrote a service. this service has tow function. here is my service code.

app.service('sharedData', function ($http) {
var data=[]
return {
    setData: function () {
        $http.get('/getData').success(function(response){
            data = response;
        })
    },
    getData: function(){
        return data;
    }
}

});

in first controller

app.controller("FirstController", function ($scope, $http,sharedData)  
  {    
     $scope.handleGesture = function ($event)
      {  
        sharedData.setData();
     };

});

in second controller:

app.controller("SecondController", function ($scope,sharedData) {
    var data=[];
    data = sharedData.getData();
}

);

in first controller setData work with out any problem but in second controller not work correctly. how to share data dynamically between tow controllers?


回答1:


You are on the right track with trying to share data between controllers but you are missing some key points. The problem is that SecondController gets loaded when the app runs so it calls sharedData.getData() even though the call to setData in the firstController does not happen yet. Therefore, you will always get an empty array when you call sharedData.getData().To solve this, you must use promises which tells you when the service has data available to you. Modify your service like below:

app.service('sharedData', function ($http, $q) {
    var data=[];
    var deferred = $q.defer();
    return {
        setData: function () {
            $http.get('/getData').success(function(response){
                data = response;
                deferred.resolve(response);
            })
        },
        init: function(){
            return deferred.promise;
        },
        data: data
    }
})

And the secondController like this:

app.controller("SecondController", function ($scope,sharedData) {
    var data=[];
    sharedData.init().then(function() {
        data = sharedData.data;
    });
});

For more info on promises, https://docs.angularjs.org/api/ng/service/$q




回答2:


You had multiple syntax problems, like service name is SharedData and you using it as SharedDataRange, the service is getting returned before the get function.

What I have done is corrected all the syntax errors and compiled into a plunkr for you to have a look. Just look at the console and I am getting the data array which was set earlier in the setter.

Javascript:

var app = angular.module('plunker', []);

app.controller("FirstController", function ($scope,sharedDateRange)  
  {    
        sharedDateRange.setData();
  });

     app.controller("SecondController", function ($scope,sharedDateRange) {
    var data=[];
    data = sharedDateRange.getData();
    console.log(data);
});


app.service('sharedDateRange', function ($http) {
var data=[];
return {
    setData: function () {
            data = ['1','2','3'];
        }
    ,
    getData: function(){
        return data;
    }
}
});

Working Example

If you want to keep sharedDataRange as the variable name and service name as sharedData have a look at this example

javascript:

var app = angular.module('plunker', []);


app.controller("FirstController", ['$scope','sharedData', function ($scope,sharedDateRange)  
  {    
        sharedDateRange.setData();
  }]);

     app.controller("SecondController", ['$scope','sharedData', function ($scope,sharedDateRange) {
    var data=[];
    data = sharedDateRange.getData();
    console.log(data);
}]);


app.service('sharedData', function ($http) {
var data=[];
return {
    setData: function () {
            data = ['1','2','3'];
        }
    ,
    getData: function(){
        return data;
    }
}
});



回答3:


You can bind the data object on the service to your second controller.

app.service('sharedData', function ($http) {
  var ret = {
    data: [],
    setData: function () {
        $http.get('/getData').success(function(response){
            data = response;
        });
    }
  };
  return ret;
});

app.controller("FirstController", function ($scope, sharedData) {
  $scope.handleGesture = function () {
    sharedData.setData();
  };
});

app.controller("SecondController", function ($scope, sharedData) {
  $scope.data = sharedData.data;
});



回答4:


What you need is a singleton. The service sharedData needs to be a single instance preferably a static object having a static data member. That way you can share the data between different controllers. Here is the modified version

var app = angular.module('app', []);

app.factory('sharedData', function ($http) {

var sharedData = function()
{
    this.data = [];   
}

sharedData.setData = function()
{
    //$http.get('/getData').success(function(response){
        this.data = "dummy";
    //})        
}

sharedData.getData = function()
{
    return this.data;   
}

return sharedData;
})
.controller("FirstController", function ($scope, $http,sharedData)  
  {
    sharedData.setData();
  })
.controller("SecondController", function ($scope,sharedData) {
    $scope.data=sharedData.getData();
});

I have removed the event for testing and removed the $http get for now. You can check out this link for a working demo:

http://jsfiddle.net/p8zzuju9/



来源:https://stackoverflow.com/questions/28956961/pass-data-between-controllers-in-angularjs-dynamically

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!