There are several ways to share data between AngularJS controllers:
1) Use AngularJS $rootScope without creating Service
2) Use depending parent and child relation between controller scopes.
3) Use AS keyword (If you are using angularJS 2.0, then you can use the “As” keyword which will pass your data from one controller to another controller)
AngularJS $rootScope is another option to share data between two controllers. This is also a way to share data across Controllers, to read or modify a global property.
See bellow example:
1 2 3 4 5 6 7 8 9 10 |
var app = angular.module('mymodule',[]); app.controller('Ctrl1', ['$scope','$rootScope', function($scope, $rootScope) { $rootScope.showBanner = true; }]); app.controller('Ctrl2', ['$scope','$rootScope', function($scope, $rootScope) { $rootScope.showBanner = false; }]); |
1 2 3 |
<div ng-controller="Ctrl1"> <div class="banner" ng-show="$root.showBanner"> </div> </div> |
As the name suggest this mechanism works with two controllers.
See bellow example:
1 2 3 4 5 6 7 |
app.controller("ParentCtrl", [ '$scope', function($scope){ $scope.title = "I'm the Parent."; }]); app.controller("ChildCtrl", [ '$scope', function($scope){ $scope.title = "I'm the Child."; }]); |
1 2 3 4 5 6 |
<div ng-controller="ParentCtrl"> <h1>{{ title }}</h1> <div ng-controller="ChildCtrl"> <h1>{{ title }}</h1> </div> </div> |
If you like FreeWebMentor and you would like to contribute, you can write an article and mail your article to freew[email protected] Your article will appear on the FreeWebMentor main page and help other developers.
Article Tags: angular js, AngularJS Controllers, Controllers