问题
I wonder if that's a bug or documented somewhere. Seems like injecting $element into controller attached by ng-view directive fails. Here's an example:
script.js:
.controller('MainCtrl', ['$route', '$routeParams', '$location', '$element',
function($route, $routeParams, $location, $element) {
// Works here
console.log('MainCtrl', $element);
this.$route = $route;
this.$location = $location;
this.$routeParams = $routeParams;
}])
.controller('BookCtrl', ['$routeParams', '$element', function($routeParams, $element) {
// Broken here
console.log('BookCtrl', $element);
this.name = "BookCtrl";
this.params = $routeParams;
}])
http://plnkr.co/edit/S7ziY6i3eMGn4RtetG0l?p=preview
回答1:
MainCtrl was injected by the $compile service which provides $element as a local. BookCtrl was injected by ngRoute which doesn't provide $element as a local. For more information on $compile injected locals, see AngularJS $compile API Reference -- controllers.
The locals that ngRoute injects are $scope, $template, and the other properties of the $resolve map.
From the ngRoute Docs:
localsA map of locals which is used by $controller service for controller instantiation. The
localscontain the resolved values of theresolvemap. Additionally thelocalsalso contain:
$scope- The current route scope.$template- The current route template HTML.The
localswill be assigned to the route scope's$resolveproperty. You can override the property name, usingresolveAsin the route definition. See $routeProvider for more info.
-- AngularJS ngRoute $route API Reference
From the $compile Docs:
controller
Controller constructor function. The controller is instantiated before the pre-linking phase and can be accessed by other directives (see require attribute). This allows the directives to communicate with each other and augment each other's behavior. The controller is injectable (and supports bracket notation) with the following locals:
$scope- Current scope associated with the element$element- Current element$attrs- Current attributes object for the element$transclude- A transclude linking function pre-bound to the correct transclusion scope:
-- AngularJS Comprehensive Directive API - controller
来源:https://stackoverflow.com/questions/34993691/trying-to-inject-element-into-ng-view-results-in-unknown-provider-error