11

I'm using Angular with ui.router and have setup a nested view. The parent view has a div whose visibility I can toggle through a function on the parent controller. I'd like to call this function from the child controller of the nested view. How would I do this?

adam0101
  • 29,096
  • 21
  • 96
  • 174

1 Answers1

12

http://plnkr.co/edit/zw5WJVhr7OKqACoJhDZw?p=preview

JS

angular
    .module("myApp", [])

    .controller("parent", function($scope) {
        $scope.parentFunction = function() {
            alert("Called a function on the parent")
        };
    })

    .controller("child", function($scope) {
        $scope.childFunction = function() {
            alert("Called a function on the child")
        };

        $scope.parentFromChild = function() {
            alert("I know this feels weird");
            $scope.parentFunction();
        };
    })

HTML

<!DOCTYPE html>
<html>

  <head>
    <script data-require="angular.js@*" data-semver="1.2.14" src="http://code.angularjs.org/1.2.14/angular.js"></script>
    <link rel="stylesheet" href="style.css" />
    <script src="script.js"></script>
  </head>

  <body ng-app="myApp">
    <div ng-controller="parent">
      <div ng-controller="child">
        <a href="#" ng-click="parentFunction()">Call Parent</a>
        <a href="#" ng-click="childFunction()">Call Child</a>
        <a href="#" ng-click="parentFromChild()">Call Parent from Child</a>
      </div>
    </div>
  </body>

</html>

The scope on controllers is prototypically inherited I believe which means if you don't redefine a function on the scope you get the same function from the parent scope if you call it (the problem is this then makes the assumption about the context of the use of this controller though it's debatable if this is really an issue assuming you don't depend on some effect from that controller in this controller).

Eloims
  • 5,106
  • 4
  • 25
  • 41
shaunhusain
  • 19,630
  • 4
  • 38
  • 51
  • If the controllers are defined like this would this still work? : `angular.module("myApp", []).controller("parent", function($scope){ //Code here });` in a separate file : `angular.module("myApp", []).controller("child", function($scope){ //Code here });` – phabtar Sep 29 '14 at 06:28
  • phabtar, what you wrote will almost work. In angular the module call has two variants, if you supply an array as the second arg it assumes you are trying to make this module, if you exclude the array like angular.module("myApp") it will just get the existing module and you can add things to it, the only caveat here is then the files need to be loaded in the correct order so the one that defines it with the dependencies comes first. Typically I keep a module per file and have a service and a few related controllers in one module/file. – shaunhusain Sep 29 '14 at 18:47
  • If the child is a directive with an isolate scope, you'll need to change it to `ng-click="$parent.parentFunction()"` – Craig Mar 11 '15 at 22:33