I don't believe there is an out-of-the-box way. ng-controller
just uses normal controller instantiation, and there is no opportunity to inject anything.
But this is an interesting "feature", which can be built, actually, relatively simply with a custom directive.
Here's an illustrative example (disclaimer: it is definitely not tested under obscure scenarios):
.directive("ngInject", function($parse, $interpolate, $controller, $compile) {
return {
terminal: true,
transclude: true,
priority: 510,
link: function(scope, element, attrs, ctrls, transclude) {
if (!attrs.ngController) {
element.removeAttr("ng-inject");
$compile(element)(scope);
return;
}
var controllerName = attrs.ngController;
var newScope = scope.$new(false);
var locals = $parse(attrs.ngInject)(scope);
locals.$scope = newScope;
var controller = $controller(controllerName, locals);
element.data("ngControllerController", controller);
element.removeAttr("ng-inject").removeAttr("ng-controller");
$compile(element)(newScope);
transclude(newScope, function(clone){
element.append(clone);
});
// restore to hide tracks
element.attr("ng-controller", controllerName);
}
};
});
The usage is as you described it:
<div ng-controller="MainCtrl">
{{name}}
<div ng-controller="SecondCtrl" ng-inject="{foo: name, bar: 'bar'}">
</div>
</div>
And, of course, the controller can have these variables injected:
.controller("SecondCtrl", function($scope, foo, bar){
});
plunker
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…