Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Call a method of a controller from another controller using 'scope' in AngularJS

I am trying to call a method of second controller in first controller by using scope variable. This is a method in my first controller:

$scope.initRestId = function(){         var catapp = document.getElementById('SecondApp');         var catscope = angular.element(catapp).scope();         catscope.rest_id = $scope.user.username;         catscope.getMainCategories();     };  

I am able to set the value of rest_id but I cannot call getMainCategories for some reason. The console shows this error:

TypeError: Object # has no method 'getMainCategories'

Is there a way to call the above method?

Edit:

I used the following approach to load two apps at the same time;

angular.bootstrap(document.getElementById('firstAppID'), ['firstApp']); angular.bootstrap(document.getElementById('secondAppID'), ['secondApp']); 

I could definitely use a service here, but I wanted to know if there are any other options to do the same!

like image 844
Arif Nadeem Avatar asked Oct 19 '13 16:10

Arif Nadeem


People also ask

Can we call controller method from another controller method?

Yes, you can call a method of another controller. The controller is also a simple class.

Can we inject one controller into another controller in AngularJS?

You can't inject controllers into one another.

What is scope on in AngularJS?

AngularJS Scope The scope is the binding part between the HTML (view) and the JavaScript (controller). The scope is an object with the available properties and methods. The scope is available for both the view and the controller.

What is a service in AngularJS?

In AngularJS, a service is a function, or object, that is available for, and limited to, your AngularJS application. AngularJS has about 30 built-in services. One of them is the $location service.


2 Answers

The best approach for you to communicate between the two controllers is to use events.

Scope Documentation

In this check out $on, $broadcast and $emit.

In general use case the usage of angular.element(catapp).scope() was designed for use outside the angular controllers, like within jquery events.

Ideally in your usage you would write an event in controller 1 as:

$scope.$on("myEvent", function (event, args) {    $scope.rest_id = args.username;    $scope.getMainCategories(); }); 

And in the second controller you'd just do

$scope.initRestId = function(){    $scope.$broadcast("myEvent", {username: $scope.user.username }); }; 

Edit: Realised it was communication between two modules

Can you try including the firstApp module as a dependency to the secondApp where you declare the angular.module. That way you can communicate to the other app.

like image 162
Praveenram Balachandar Avatar answered Oct 03 '22 06:10

Praveenram Balachandar


Here is good Demo in Fiddle how to use shared service in directive and other controllers through $scope.$on

HTML

<div ng-controller="ControllerZero">     <input ng-model="message" >     <button ng-click="handleClick(message);">BROADCAST</button> </div>  <div ng-controller="ControllerOne">     <input ng-model="message" > </div>  <div ng-controller="ControllerTwo">     <input ng-model="message" > </div>  <my-component ng-model="message"></my-component> 

JS

var myModule = angular.module('myModule', []);  myModule.factory('mySharedService', function($rootScope) {     var sharedService = {};      sharedService.message = '';      sharedService.prepForBroadcast = function(msg) {         this.message = msg;         this.broadcastItem();     };      sharedService.broadcastItem = function() {         $rootScope.$broadcast('handleBroadcast');     };      return sharedService; }); 

By the same way we can use shared service in directive. We can implement controller section into directive and use $scope.$on

myModule.directive('myComponent', function(mySharedService) {     return {         restrict: 'E',         controller: function($scope, $attrs, mySharedService) {             $scope.$on('handleBroadcast', function() {                 $scope.message = 'Directive: ' + mySharedService.message;             });         },         replace: true,         template: '<input>'     }; }); 

And here three our controllers where ControllerZero used as trigger to invoke prepForBroadcast

function ControllerZero($scope, sharedService) {     $scope.handleClick = function(msg) {         sharedService.prepForBroadcast(msg);     };      $scope.$on('handleBroadcast', function() {         $scope.message = sharedService.message;     }); }  function ControllerOne($scope, sharedService) {     $scope.$on('handleBroadcast', function() {         $scope.message = 'ONE: ' + sharedService.message;     }); }  function ControllerTwo($scope, sharedService) {     $scope.$on('handleBroadcast', function() {         $scope.message = 'TWO: ' + sharedService.message;     }); } 

The ControllerOne and ControllerTwo listen message change by using $scope.$on handler.

like image 34
Maxim Shoustin Avatar answered Oct 03 '22 06:10

Maxim Shoustin