Trying to inject $element into ng-view results in

2019-02-28 17:15发布

问题:

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:

locals

A map of locals which is used by $controller service for controller instantiation. The locals contain the resolved values of the resolve map. Additionally the locals also contain:

  • $scope - The current route scope.
  • $template - The current route template HTML.

The locals will be assigned to the route scope's $resolve property. You can override the property name, using resolveAs in 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