如何在子指令中访问父控制器的功能



如何从子指令中的父控制器调用函数?

我的控制器看起来像这样。

angular.module('myVillage')
.controller('myVillageController', myVillageController);
function myVillageController($scope, $q, $element, $timeout) {
function moveHome() {
console.log("moved home")
}
}

我的指令看起来像这样。

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() {
//....
}
}

我想在 move-village 指令中调用 moveHOme 函数。

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

你可以试试

$scope.$parent.moveHome();

从子控制器。

谢谢你们,人们,试图回答。

由于无法访问父控制器范围,因此我无法在myVillagecontroller中传递$scope。

这是我的答案。

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'
}
}

最新更新