我有一對嵌套的指令。我試圖保持一致並使用controllerAs語法。但我正在努力尋找一種乾淨的方式讓孩子們調用父母方法,這種父母方法不包括父母在其範圍上放置看似隨機的功能。在指令中使用控制器的語法訪問父項方法
angular.module('app', [])
.directive('parent', function(){
return {
restrict: 'EA',
controller: 'ParentController',
controllerAs: 'parentCtrl',
}
})
.directive('child', function(){
return {
restrict: 'EA',
require: '^parent',
controller: 'ChildController',
controllerAs: 'childCtrl'
}
})
.controller('ParentController', function($scope){
var ctrl = this;
ctrl.type = "hot";
ctrl.nonInheritedFunction = nonInheritedFunction;
$scope.inheritedFunction = inheritedFunction; // <-- trying to avoid this
function nonInheritedFunction(type){
ctrl.type = type;
if(ctrl.type == 'cold'){
//... do some Parent related things
}
}
function inheritedFunction(type){
// to illustrate that it does the same thing. Not a solution
ctrl.nonInheritedFunction(type);
}
})
.controller('ChildController', function($scope){
var ctrl = this;
ctrl.doAction = doAction;
function doAction(action){
if(action == 'flip_temperature'){
// bah
$scope.parentCtrl.nonInheritedFunction('hot');
// much cleaner feeling
$scope.inheritedFunction('hot');
// wishing I could do something like
// ctrl.nonInheritedFunction('hot');
}
}
/**
* template has access to type through `parentCtrl.type`
* and the function through `parentCtrl.nonInheritedFunction`
*
* The only access the ChildController has is `$scope.parentCtrl.type`
* Is there a way to keep $scope out of the equation?
*/
})