Nithesh S D Nithesh S D - 6 months ago 17
AngularJS Question

How to fetch scope value from one controller to another controller in angular JS

How to fetch the scope value from one controller to another controller
html

<button class="btn btn-info" ng-click="setLanguage('en')">English</button>
<button class="btn btn-info" ng-click="setLanguage('de')">Danish</button>


Javascript

.controller('demoCtrl', function($scope) {
$scope.setLanguage = function(language) {
$scope.language = language;
}
});

Answer

You can use a service to get the value set by one controller into another controller.

.service('someService', function () {
  this.language = null;
})

Controller

.controller('demoCtrl', function($scope, $rootScope, someService) {
    $scope.setLanguage = function(language) {
        $scope.language = language;
        someService.language = language;
        $rootScope.$broadcast('languageChanged');
    } 
});

In the other controller

.controller('someCtrl', function($scope, $rootScope, someService) {
    $rootScope.$on('languageChanged', function () {
        $scope.language = someService.language;
    }
});