Search code examples
angularjsangularjs-controller

Calling function in child controller from parent controller


I have a controller nested in another controller.

<div ng-controller="manufacturerController" ng-cloak>
    <div ng-controller="contractController" ng-cloak>
        <div data-ng-if="item" class="panel panel-default">
            <div class="panel-heading text-center">
                <span class="h3">Contract</span>
            </div>
        </div>
    </div>
    <button data-ng-if="item && !ajaxOut" class="btn btn-success" data-ng-click="saveItem()">Save</button>
</div>

saveItem() is called via the button and the code is in the manufacturerController:

    $scope.saveItem = function () {
        $scope.ajaxOut = true;
        $scope.saveContracts();
    };

But the function saveContracts() is in the contractController. I want to call the contractController.saveContracts() from manufacturerController.saveItem().

According to here I should be able to call the parent method fine: How to call a function from another controller in angularjs?

But the save is freezing the browser. What am I doing wrong and how do I fix it?


Solution

  • One way is broadcasting an event on scope:

    function ParentController($scope) 
    {
      $scope.$broadcast('someEvent', args);
    }
    
    function ChildController($scope) 
    {
      $scope.$on('someEvent', function(event, args) {});
      // another controller or even directive
    }
    

    Scope Events Propagation

    Scopes can propagate events in similar fashion to DOM events. The event can be broadcasted to the scope children or emitted to scope parents.

    — AngularJS Developer Guide - Scope Event Propagation

    For more information, see Can one controller call another?