1st way: use services
Services are singletons and you can pass data through services. For example, let's call our service dataservice
:
angular
.module('app')
.controller('FirstController', ['dataservice']);
function FirstController(dataservice) {
dataservice.dataToPass = 'data to pass through controllers';
}
And you can get this data from second controller like this:
angular
.module('app')
.controller('SecondController', ['dataservice']);
function SecondController(dataservice) {
let dataFromFirstController = dataservice.dataToPass;
}
2nd way: use $emit/$broadcast (only if controllers are the parent and the child)
You can pass data up via $emit
or down via $broadcast
($emit and $broadcast works similar, I'll show the example only with $broadcast). If FirstController
is the parent and SecondController
is the child, you can pass data through them like this:
angular
.module('app')
.controller('FirstController', ['$scope']);
function FirstController($scope) {
$scope.$broadcast('passDataFromParentToChild', 'Data from FirstController');
}
And get data in SecondController
:
angular
.module('app')
.controller('SecondController', ['$scope']);
function SecondController($scope) {
$scope.$on('passDataFromParentToChild', function (event, data) {
console.log(data); // will be "Data from FirstController"
});
}
3rd way: use $scope.$parent (only if controllers are the parent and the child)
If you want to change variable of parent controller from the child controller, here is the easiest way (let's assume that FirstController
is the parent of SecondController
):
angular
.module('app')
.controller('FirstController', ['$scope']);
function FirstController($scope) {
$scope.varFromParentController = 'First';
}
Let's change $scope.varFromParentController
from SecondController
:
angular
.module('app')
.controller('SecondController', ['$scope']);
function SecondController($scope) {
$scope.$parent.varFromParentController = 'Second';
}