Seeta Ram Yadav
Seeta Ram Yadav

Reputation: 1083

How to access function of a parent controller inside the child directive

How can I call a function from parent controller inside the child directive?

my controller looks something like this.

angular.module('myVillage')
  .controller('myVillageController', myVillageController);

function myVillageController($scope, $q, $element, $timeout) {
  function moveHome() {
    console.log("moved home")
  }
}

my directive looks something like this.

angular
  .module('myVillage')
  .directive('myVillagModal', myVillagModal);

var vm = this,

  cachedKeys = {},
  limitInit = 500;
function myVillagModal(myVillage, $filter) {
  return {
    restrict: 'E',
    templateUrl: myVillagelTemplateUrl,
    bindToController: true,
    scope: {
      items: '=',
      selectedItems:'=',
      selectedItemsChanged: '&'
    },
    transclude: true,
    controller: myVillageController,
    controllerAs: 'vm'
  };

  function myVillageController() {
    //....
  }
}

I want to call the moveHOme function inside the move-village directive.

<div ng-controller="myVillageController">
  <move-village></move-village>
  </div>

Upvotes: 0

Views: 39

Answers (2)

Seeta Ram Yadav
Seeta Ram Yadav

Reputation: 1083

Thank you, people, for trying to answer.

I was missing to pass $scope inside the myVillagecontroller due to that I was not able to access parent controller scope.

here is my answer.

angular
  .module('myVillage')
  .directive('myVillagModal', myVillagModal);

var vm = this,

  cachedKeys = {},
  limitInit = 500;
function myVillagModal(myVillage, $filter) {
  return {
    restrict: 'E',
    templateUrl: myVillagelTemplateUrl,
    bindToController: true,
    scope: {
      items: '=',
      selectedItems:'=',
      selectedItemsChanged: '&'
    },
    transclude: true,
    controller: myVillageController,
    controllerAs: 'vm'
  };

  function myVillageController($scope) {
    //$scope.$parent now gives the scope of parent controller
    //....
    $scope.$parent.moveHome(); //this gives 'moved home'
  }
}

Upvotes: 0

Noor A Shuvo
Noor A Shuvo

Reputation: 2807

You can try

$scope.$parent.moveHome();

from the child controller.

Upvotes: 1

Related Questions