Search code examples
angularjsangularjs-directiveangularjs-scope

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!


Solution

  • 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.