user1943020
user1943020

Reputation:

How can I pass call a function on a child controller from the parent and pass a parameter?

I have an HTML page and a parent controller:

<a data-ng-click="callChild('x')"></a>

$scope.callChild = function (task) {

}

How can I make it so that when the link is clicked then the function callChild is executed in a child controller and the argument is passed to the child controller function?

Upvotes: 0

Views: 406

Answers (1)

Maxim Shoustin
Maxim Shoustin

Reputation: 77930

The parent controller can notify child controller by using $broadcast.

Here is some example Live Demo:

HTML

<div ng-controller="ParentCtrl">
    
    <a data-ng-click="callChild('x')">Click me</a>
    
    <div ng-controller="ChildCtrl">            
      
    </div>
</div>

JS

var fessmodule = angular.module('myModule', []);

function ParentCtrl($scope, $timeout) {    
  
     $scope.callChild = function (val) {
       $scope.$broadcast('someEvent', val);
    };
}

function ChildCtrl($scope) { 
    $scope.$on('someEvent', function (event, val) {
        alert('from child ' + val);
    });
}

Reference

$broadcast -- dispatches the event downwards to all child scopes,

$emit -- dispatches the event upwards through the scope hierarchy.

Upvotes: 2

Related Questions