父子控制器
Parent and child controllers
有两个控制器,父控制器和子控制器。
<div ng-controller="firstCtrl as first">
<div ng-controller="secondCtrl as second"></div>
</div>
JS:
app.controller('firstCtrl', function() {
this.func = function() {
//some code
};
});
app.controller('secondCtrl', function() {
this.parent.func(some_data);//thats what I need to do
});
是否可以在不使用工厂或 $scope.$parent
的情况下做到这一点?
Is it possible to do this without using factory or $scope.$parent?
不,你不能。
附带说明一下,我不太喜欢使用 $scope.$parent
。在一个大的应用程序中,你真的可以通过叠加这样的东西来失去对你的应用程序的控制。
如果您想在控制器之间共享一个功能,您可能需要使用 service
。
将 $scope 注入到您的 parent 控制器和 child 控制器中,并将 parent 的方法保存到 $scope 中,如下所示:
Parent:
app.controller('firstCtrl','$scope',function(){
$scope.yourFunctionName = function(some_data){
//some code
};
});
并在 child 中按照以下方式调用 parent 控制器方法:
Child
app.controller('secondCtrl', '$scope',function(){
$scope.yourFunctionName(some_data);//thats what I need to do
};
});
虽然如前所述,service/factory 在这里可能更好,但如果您想要其他选项,可以使用组件。示例:
angular.module('app')
.component('parent', {
controller: function() {
var $ctrl = this;
$ctrl.doStuff = function() {};
},
templateUrl: '/view.html'
});
angular.module('app')
.component('child', {
require: {
parent: '^parent'
},
controller: function() {
var $ctrl = this;
$ctrl.$onInit() = function() {
$ctrl.parent.doStuff();
};
},
templateUrl: '/view.html'
});
添加组件要求的父项,然后在 $onInit 函数中您将可以访问其上的任何 data/methods。希望对您有所帮助。
有两个控制器,父控制器和子控制器。
<div ng-controller="firstCtrl as first">
<div ng-controller="secondCtrl as second"></div>
</div>
JS:
app.controller('firstCtrl', function() {
this.func = function() {
//some code
};
});
app.controller('secondCtrl', function() {
this.parent.func(some_data);//thats what I need to do
});
是否可以在不使用工厂或 $scope.$parent
的情况下做到这一点?
Is it possible to do this without using factory or $scope.$parent?
不,你不能。
附带说明一下,我不太喜欢使用 $scope.$parent
。在一个大的应用程序中,你真的可以通过叠加这样的东西来失去对你的应用程序的控制。
如果您想在控制器之间共享一个功能,您可能需要使用 service
。
将 $scope 注入到您的 parent 控制器和 child 控制器中,并将 parent 的方法保存到 $scope 中,如下所示:
Parent:
app.controller('firstCtrl','$scope',function(){
$scope.yourFunctionName = function(some_data){
//some code
};
});
并在 child 中按照以下方式调用 parent 控制器方法:
Child
app.controller('secondCtrl', '$scope',function(){
$scope.yourFunctionName(some_data);//thats what I need to do
};
});
虽然如前所述,service/factory 在这里可能更好,但如果您想要其他选项,可以使用组件。示例:
angular.module('app')
.component('parent', {
controller: function() {
var $ctrl = this;
$ctrl.doStuff = function() {};
},
templateUrl: '/view.html'
});
angular.module('app')
.component('child', {
require: {
parent: '^parent'
},
controller: function() {
var $ctrl = this;
$ctrl.$onInit() = function() {
$ctrl.parent.doStuff();
};
},
templateUrl: '/view.html'
});
添加组件要求的父项,然后在 $onInit 函数中您将可以访问其上的任何 data/methods。希望对您有所帮助。