问题描述
我在应用程序中使用controllerAs语法,我想从子控制器访问父控制器的功能,我知道这可以通过注入$ scope来实现,但是考虑到Angular竭尽全力从代码中摆脱$ scope,我想知道是否有一种更优雅的方式来执行此操作而不注入$ scope?
I am using controllerAs syntax in my application, I want to access parent controller's function from child controller, I know this is achievable by injecting $scope, however considering Angular has tried so hard to get rid of the $scope from code, I'd like to know if there is a more elegant way of doing this without injecting $scope?
这是HTML的示例:
<div ng-controller="AppCtrl as app">
<div ng-controller="ChildCtrl as child">
</div>
</div>
以及相应的控制器:
angular.module('test').controller('AppCtrl', function () {
var vm = this;
vm.log = function() {
console.log("Output");
}
}
angular.module('test').controller('ChildCtrl', function () {
var vm = this;
// Here I want to access parent's log() function
}
我知道我可以注入$ scope,然后通过 $ scope.app.log()
访问日志功能,但是有一种更好的方式来访问日志而无需注入 $ scope?
I know I can inject $scope and then access the log function by $scope.app.log()
, but is there a bettter way to access log without injecting the $scope?
推荐答案
一种选择是使用Angular 1.5组件(文档).
One option would be to use Angular 1.5 components (docs).
在子组件中看起来像这样:
It would look something like this in child component:
.component('childComponent', {
require: {
parentCtrl: '^ parentCtrl'
}
controller: function() {
this.parentCtrl.anyMethod(); //here we are accessing parent's controller properties
}
...
});
这篇关于从子控制器访问父控制器成员的一种优雅方法是什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!