AngularJS - 手动使用注入器注入服务时出错

AngularJS - Error while manually using injector to inject a service

我在尝试手动使用 angular.injector 注入正在打开对话框的服务时遇到问题,而该对话框又在其模板内部使用指令,该指令使用动态模板。

我在控制台中遇到的错误是:

1: Unknown provider: $rootElementProvider <- $rootElement <- $location <- $anchorScroll <- ngIncludeDirective <- $location

2: Controller 'ngInclude', required by directive 'ngInclude', can't be found!

这里是plunker demonstrating the problem

var customSvc = angular.injector(['ng', 'pluginApp']).get("customSvc");
customSvc.testOpenDialog(100, scope);

我还尝试构建 url 并将其指定为指令属性并从 templateUrl 函数访问它,但在这种情况下它也失败了,因为我收到的值只是变量的名称,不是内容。

如果我避免通过 angular.injector 注入服务,代码可以工作,但是由于应用程序的性质,我无法避免它,此外,我有兴趣了解背后的原因这个错误,如果有人好心地解释一下这个问题。

在您的 gedContextMenu.js 文件中,进行以下更改

注入pluginApp

angular.module('gedContextMenuApp', ['ui.bootstrap', 'mgcrea.ngStrap.popover','pluginApp']);

在您的 gedContextMenu 菜单指令中注入服务 customSvc

angular.module('gedContextMenuApp').directive('gedContextMenu',['$log','$templateCache', '$uibModal', 'customSvc', function($log, $templateCache, $uibModal, customSvc) {
  return {
    restrict: 'AE',
    scope: {
      gedContextData: '='
    },
    template: "<button class='fa fa-cog' bs-popover data-template='{{popoverTemplate}}' data-auto-close='1' data-placement='bottom' data-animation='am-flip-x'></button>",
    controller: function($scope) {
      $scope.popoverTemplate = 'popoverTemplate.html';

      $scope.executePlugin = function($event, contextItem) {
        var propName = contextItem.action;
        $scope.contextItem = contextItem;
        $log.info('property name ' + propName + ' used to trigger event ', $event.type);
        $scope[propName] = $event;
      }

      $scope.click = function($event, contextItem) {
        $scope.executePlugin($event, contextItem);
      }
    },
    link: function(scope, element, attrs) {
        scope.$watch('openDialog', function(event) {
        if (event && event.type === 'click') {
          console.log(customSvc);
          // var customSvc = angular.injector(['ng', 'pluginApp']).get("customSvc");

          //angular.injector(['ng', function($provide) {
          //  var $rootElement = angular.element(document.querySelector('body'));
          //  $provide.value('$rootElement', $rootElement);
          //}]).invoke(function($injector) {
          //  var localRootElement = $injector.get('$rootElement');
          //});

          // customSvc.testOpenDialog(100, scope);
          //customSvc.testDirettivaConfirm(100, scope);

        }
      });
    }
  }
}]);

解决方法是通过以下方式注入服务:

   var customSvc = angular.injector(['ng', 'pluginApp', 
      function($provide) {
        var $rootElement = angular.element(document.querySelector('body'));
        $provide.value('$rootElement', $rootElement);
      }]).get("customSvc");

这是工作plunker