I have a function defined in a controller , I want to call it in another controller. I tried to attach it to the $rootscope so I can see in the other controller , but I couldn't . Is there a way for calling it, without attaching it to the $rootscope?
- both controllers have parent child relationship or both are siblings?dhavalcengg– dhavalcengg2014-12-28 15:49:22 +00:00Commented Dec 28, 2014 at 15:49
- 1In that case it is advisable to create a service and use across controllers.dhavalcengg– dhavalcengg2014-12-28 16:08:19 +00:00Commented Dec 28, 2014 at 16:08
3 Answers
As far as I know in AngularJS you can share info between controllers in 3 ways:
1 - Creating a Service.
2 - Creating a function linked to $rootScope.
3 - Using events ($broadcast and $on). I use a lot this method in my projects.
I think your problem is that you don't instantiate the controllers in the proper order or one of them is never instantiated, therefore the function you want to link to $rootScope in that controller or the broadcast event never fires.
E.G If you want to call a function linked to $rootScope in the 2 controller from the first one, it is impossible because the 2 controller is instantiated after the first one.
This case happens when you make calls on application runtime.
I will implement your method with some changes:
HTML:
<div ng-controller="MyCtrl_1"></div> <div ng-controller="MyCtrl_2"> <button ng-click="send()">Send Mess</button> </div> JS:
var myApp = angular.module('myApp',[]); function MyCtrl_1($scope, $rootScope) { $scope.$on('RenderPage', function (event, PageId) { $scope.RenderPage = PageId; alert($scope.RenderPage); }); }; function MyCtrl_2($scope, $rootScope) { $scope.MasterPageId = 10; $scope.send = function(){ $rootScope.$broadcast('RenderPage', $scope.MasterPageId); } };
Use carefully $broadcast and $emit, because has different behavior each one.
Try here: http://jsfiddle.net/1ypkb4s9/
Otherwise, post your error.
Comments
Simply wrap them with a "father controller":
HTML:
<div ng-app="myApp" ng-controller="myOuterCtrl"> <div ng-controller="myInnerCtrl1"> <button ng-click="outerClick()">Outer Click</button> </div> <div ng-controller="myInnerCtrl2"> <button ng-click="innerTwoClick()">Inner Click</button> </div> </div> JS:
angular.module('myApp', []). controller('myOuterCtrl', function ($scope) { $scope.outerClick = function () { console.log('outer click'); } }). controller('myInnerCtrl1', function ($scope) { // nothing here!! }). controller('myInnerCtrl2', function ($scope) { $scope.innerTwoClick = function () { console.log('inner two click'); } }); Comments
if you want to use the same function in two or more controllers you might need a service.
or use events
function firstCtrl($scope) { $scope.$broadcast('someEvent', [1,2,3]); } function secondCtrl($scope) { $scope.$on('someEvent', function(event, mass) { console.log(mass); }); }