Reputation: 103
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;
}
});
Upvotes: 1
Views: 5051
Reputation: 31
If we want to call example method of:
"test1 DIV controller"
from:
"test2 DIV controller"
then we can write above method.
angular.Element(document.getelementByID('testDIV')).scope().example method name();
in test2DIVcontroller.
For Example :
<DIV ID="test1DIV" ng-controller="test1DIV controller"></DIV>
<DIV ID="test2DIV" ng-controller="test2DIV controller"></DIV>
Upvotes: 0
Reputation: 662
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;
}
});
Upvotes: 1
Reputation: 804
You can share data between controllers with the help of either a service or you can use $emit() and $broadcast() functions.
There is a listener function in AngularJS $on() which will always be listening to the broadcast and emit events.
The syntax for the above function :
$scope.$emit(‘name1’,{}); //here you can send your data
$scope.$broadcast(‘name2’,{});
$scope.$on(‘name2’,function(event,args){
});
When using a service you can simply inject the service into your two controllers and share the data.
.service('someService', function () {
var self=this;
self.language = '';
});
.controller('firstCtrl', function($scope, someService) {
$scope.setLanguage = function(language) {
$scope.language = language;
someService.language = language;
}
});
.controller('secondCtrl', function($scope, someService) {
$scope.language = someService.language;
});
Upvotes: 0