0

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?

Hadi J
  • 16,989
  • 4
  • 36
  • 62

4 Answers4

0

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;
    }
}
});
V31
  • 7,626
  • 3
  • 26
  • 44
0

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;
});
Steven Wexler
  • 16,589
  • 8
  • 53
  • 80
0

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

  • why not change data in secondCtrl after occur event on firstCtrl ? event on firstCtrl is mouse click or any thing. – Hadi J Mar 10 '15 at 08:19
  • I updated the answer above. Sorry I didn't see that firstController can update data multiple times, in this case, you can just bind to the data on the service and the data in your secondController will be updated accordingly. – Dominique Canlas Mar 10 '15 at 18:27
0

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/

Farhan Rahman
  • 206
  • 2
  • 12