Parent and child controllers
Having two controllers, parent and child.
<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
});
Is it possible to do this without using a factory or $scope.$parent
?
Is it possible to do this without using factory or $scope.$parent?
No, you can't.
As a side note, I don't really like using $scope.$parent
. in a big app, you can really loose the control of your app by imbricating such things.
If you would like to share a function between controllers, you may want to use a service
instead.
Inject $scope into your parent controller and in child controller as well, and save method of parent into $scope like following:
Parent:
app.controller('firstCtrl','$scope',function(){
$scope.yourFunctionName = function(some_data){
//some code
};
});
and in child do it like following to call parent controller method:
Child
app.controller('secondCtrl', '$scope',function(){
$scope.yourFunctionName(some_data);//thats what I need to do
};
});
Although as mentioned a service/factory is probably better here but if you want another option you could use components. Example:
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'
});
Add the parent as to the components require then in the $onInit function you'll have access to any data/methods on it. Hope that helps.
链接地址: http://www.djcxy.com/p/77566.html上一篇: angularjs服务混乱
下一篇: 父母和孩子控制器