first method
In angularJS, by default, when a property cannot be found in the current scope, it will be searched in the parent scope, if not found until $rootScope is found .
If it cannot be found in $rootScope, the program still runs, but the view is not updated.
//Javascript app.controller('ParentController', function($scope) { $scope.person = {greeted: false}; }); app.controller('ChildController', function($scope) { $scope.sayHello = function() { $scope.person.name = 'Ari Lerner'; }; }); //HTML <div ng-controller="ParentController"> <div ng-controller="ChildController"> <a ng-click="sayHello()">Say hello</a> </div> {{ person }} </div> //result {"greeted":false, "name": "Ari Lerner"}
The second method
$on, $emit and $broadcast makes the transfer of event and data between controllers simple.
$emit can only pass event and data to the parent controller.
$broadcast can only pass event and data to the child controller.
$on is used To receive event and data //
JavaScript app.controller('ParentController', function($scope) { $scope.$on('$fromSubControllerClick', function(e,data){ console.log(data); // hello }); }); app.controller('ChildController', function($scope) { $scope.sayHello = function() { $scope.$emit('$fromSubControllerClick','hello'); }; }); //HTML <div ng-controller="ParentController"> <div ng-controller="ChildController"> <a ng-click="sayHello()">Say hello</a> </div> </div>
The third way
utilizes the characteristics of the service singleton pattern in angularJS. The service provides a way to maintain data throughout the life cycle of the application,
communicate between controllers, and ensure data consistency sex.
JavaScript var myApp = angular.module("myApp", []); myApp.factory('Data', function() { return { name: "Ting" } }); myApp.controller('FirstCtrl', function($scope, Data) { $scope.data = Data; $scope.setName = function() { Data.name = "Jack"; } }); myApp.controller('SecondCtrl', function($scope, Data) { $scope.data = Data; $scope.setName = function() { Data.name = "Moby"; } });