Trying to inject $element into ng-view results in Unknown Provider error

我与影子孤独终老i 提交于 2019-12-02 12:45:29

问题


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



来源:https://stackoverflow.com/questions/34993691/trying-to-inject-element-into-ng-view-results-in-unknown-provider-error

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!