简体   繁体   中英

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?

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?

You can use $broadcast from the parent to a child:

function ParentCntl($scope) {

    $scope.msg = "";
    $scope.get = function(){
        $scope.$broadcast ('someEvent');
        return  $scope.msg;        
    }
}

function ChildCntl($scope) {               
    $scope.$on('someEvent', function(e) {  
        $scope.$parent.msg = $scope.get();            
    });

    $scope.get = function(){
        return "xyz";    
    }
}

Look up "$on $emit $broadcast angularjs". Tons and tons of examples out there.

(As I said previously in my comment, you don't want controllers to have any knowledge of each other. One dispatches an event/notification, another hears it, sort of like somebody you don't know just standing up in a room and shouting a name you're interested in).

Each is used for a different context. Depending on what you're doing, you might use one or the other. Understanding each of those is super important to the AngularJS developer (and the overall concept to any UI dev).

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM