在父上下文中调用父控制器的函数
Calling a parent controller's function in the parent's context
我需要我的父控制器函数 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 中应该有一个直接的解决方案。
您始终可以为指令创建局部作用域,并使用此“&”将父函数绑定到局部作用域。假设这是你的 html
<child get-data="parentCtrl.getDataInParent(params)"></child>
这应该是您的指令代码。
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"});
}
}
工作的 Plunker:https://plnkr.co/edit/4n61WF4JN3eT2QcdnnTw?p=preview
我需要我的父控制器函数 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 中应该有一个直接的解决方案。
您始终可以为指令创建局部作用域,并使用此“&”将父函数绑定到局部作用域。假设这是你的 html
<child get-data="parentCtrl.getDataInParent(params)"></child>
这应该是您的指令代码。
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"});
}
}
工作的 Plunker:https://plnkr.co/edit/4n61WF4JN3eT2QcdnnTw?p=preview