user1943020
user1943020

Reputation:

How can I call a function in a child controller in AngularJS?

In my code I have the following:

<html data-ng-controller="appController"
      data-ng-keydown="callFunction($event)">

In the single page application I open a page and it has a detailController with the following:

    $scope.callFunction = function (eventNew) {
        var a = 0;
        if (eventNew.which == 39)
            alert('Right arrow key pressed');
    }

But this function is not getting called. The only time it is called is if the function is coded in the appController.

How can I call that function in my detailController controller?

Upvotes: 0

Views: 126

Answers (2)

idursun
idursun

Reputation: 6335

Instead of directly invoking the method, you can $broadcast a keydown event down to child scopes and handle key down event.

<html data-ng-controller="appController"
      data-ng-keydown="$broadcast('keydown',$event)">

 $scope.$on('keydown', function(event, args) {
    $window.alert('key was down ' + args.which)
  })

Upvotes: 2

Marian Ban
Marian Ban

Reputation: 8188

You can't because the parent controller (app) does not have access to your child controller's scope. If you want to define your callFunction on detailController's scope then you have to call it from the detail controller.

<html data-ng-controller="appController" >
    <body ng-controller="detailController" data-ng-keydown="callFunction($event)">
    </body>
</html>

Upvotes: -1

Related Questions