我需要父控制器函数 getDataInParent 才能在父控制器的上下文中调用。
样品:
在父指令模板中正确设置了这样的子指令:
<child get-data="parentCtrl.getDataInParent"></child>
这是我的控制器实现的简单模型(请参阅getDataInParent中的注释):
// *** parent controller
controller('parentController', [...., function(){
var that = this;
that.someData = ...;
that.getDataInParent = function(someArgs){
// Here I need to access "that.someData" and other
// properties/methods of this parent controller. But I can't!
// Because this method doesn't seemed to be called in the context of this controller.
};
};]
// *** child controller
controller('childController', [...., function(){
var that = this;
// Hooked up correctly and am able to call the parent's function like this:
var dataFromParent = $scope.getData().(someArgs);
};]
这似乎是很多人会遇到的非常常见的情况,所以我希望在Angular中应该有一个直接的解决方案。
答案 0 :(得分:1)
您始终可以为指令创建本地范围&amp;使用“&amp; ”将父函数绑定到本地范围。假设这是你的html
angular
.module('SampleApp')
.directive('child', child);
/* @ngInject */
function child() {
var directive = {
restrict: 'E',
templateUrl: 'templateUrl',
scope: {
getData : '&'
},
link: linkFunc,
controller: 'Controller',
controllerAs: 'vm'
};
return directive;
function linkFunc(scope, el, attr, ctrl) {
// Calling parent method here
var dataFromParent = $scope.getData({params: "SomeParams"});
}
}
这应该是你的指令代码。
Dim diff = DateTime.Now - DateTime.Parse("September 27, 2016")
MsgBox diff.Days
Working Plunker:https://plnkr.co/edit/4n61WF4JN3eT2QcdnnTw?p=preview