AngularJS 控制器可以从同一模块中的另一个控制器继承吗? [英] Can an AngularJS controller inherit from another controller in the same module?
问题描述
在模块内,控制器可以从外部控制器继承属性:
Within a module, a controller can inherit properties from an outside controller:
var app = angular.module('angularjs-starter', []);
var ParentCtrl = function ($scope, $location) {
};
app.controller('ChildCtrl', function($scope, $injector) {
$injector.invoke(ParentCtrl, this, {$scope: $scope});
});
示例通过:死链接:http://blog.omkarpatil.com/2013/02/controller-inheritance-in-angularjs.html
Example via: Dead link: http://blog.omkarpatil.com/2013/02/controller-inheritance-in-angularjs.html
模块中的控制器也可以继承自兄弟节点吗?
Can also a controller inside a module inherit from a sibling?
var app = angular.module('angularjs-starter', []);
app.controller('ParentCtrl ', function($scope) {
//I'm the sibling, but want to act as parent
});
app.controller('ChildCtrl', function($scope, $injector) {
$injector.invoke(ParentCtrl, this, {$scope: $scope}); //This does not work
});
第二个代码不起作用,因为 $injector.invoke
需要一个函数作为第一个参数,并且没有找到对 ParentCtrl
的引用.
The second code does not work since $injector.invoke
requires a function as first parameter and does not find the reference to ParentCtrl
.
推荐答案
可以,但是你必须使用 $controller
服务来实例化控制器:-
Yes, it can but you have to use the $controller
service to instantiate the controller instead:-
var app = angular.module('angularjs-starter', []);
app.controller('ParentCtrl', function($scope) {
// I'm the sibling, but want to act as parent
});
app.controller('ChildCtrl', function($scope, $controller) {
$controller('ParentCtrl', {$scope: $scope}); //This works
});
这篇关于AngularJS 控制器可以从同一模块中的另一个控制器继承吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!