sachin sachin - 7 months ago 10
Javascript Question

Update the value of variable in one controller from another controller after http.get?

I have two controllers. I want to update a variable from one controller to another controller using service but its not updating.

I want the variable

$scope.names
in controller 'select' to update in the controller 'current' and display it

app.controller('select', ['$scope', '$http', 'myService', function($scope,$http, myService) {
$http.get('/myapp/stocknames').
success(function(data) {
$scope.names=data;
myService.names=data;
});
}]);


I am using myService to exchange the data between the two controllers. I have declared in my service.

app.service('myService', function($http, $rootScope) {
this.names=[]
});


app.controller('current', ['$scope', '$http', 'myService', function($scope,$http, myService) {
$scope.names=myService.names;
console.log($scope.names);
}]);


Can you please help. How should I make the current controller update the data once the
$scope.names
variable in the select controller is updated?

According to me what I am doing should work :-/

Answer

There are many way to archive this:

First: By watching for the service variable data change

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

app.service('dataService', function() {
  this.serviceData = "test";
});

app.controller('MainCtrl', function($scope, dataService) {
  $scope.mainClickHandler = function(mainData) {
    dataService.serviceData = mainData;
  }
});


app.controller('SubCtrl', function($scope, dataService) {
  $scope.name = 'World';

  $scope.getServiceData = function() {
    return dataService.serviceData;
  }

  $scope.$watch("getServiceData()", function(newValue, oldValue) {
    if (oldValue != newValue) {
      $scope.name = newValue;
    }
  });
});

http://plnkr.co/edit/G1C81qvDD179NILMMxWb

Second:

Using event broadcast

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

app.factory('dataService', function($rootScope) {
  var serviceData = {
    "mydata": "test"
  };

  $rootScope.$watch(function() {
    return serviceData.mydata;
  }, function(newValue, oldValue, scope) {
    $rootScope.$broadcast('dataService:keyChanged', newValue);
  }, true);

  return serviceData;

});

app.controller('MainCtrl', function($scope, dataService) {
  $scope.mainClickHandler = function(mainData) {
    dataService.mydata = mainData;
  }
});


app.controller('SubCtrl', function($scope, $rootScope, dataService) {
  $scope.name = 'World';

  $rootScope.$on('dataService:keyChanged', function currentCityChanged(event, value) {
    console.log('data changed', event, value);
    $scope.name = value;
  });

});

http://plnkr.co/edit/tLsejetcySSyWMukr89u?p=preview

Third:

Using callback

Comments