【问题标题】:Directive not working when separate module created创建单独的模块时指令不起作用
【发布时间】:2015-12-13 18:34:21
【问题描述】:

背景

我正在构建一个 Angular 应用程序,其文件结构推荐为 here。 一个快速的总结是,你的应用程序的每个部分都被拆分成迷你模块,以保持它的可维护性。我认为这是一个很棒的想法,因为我以前开发过的应用程序都有大量难以破译的代码库。

问题

我有一些控制器、服务和路由,刚开始构建应用程序的第一个指令时,我不断收到此错误

错误:[$injector:unpr] 未知提供者:提供者

我已经阅读了unknown provider error doc,但没有找到任何东西。

代码

这是我的代码

指令

angular.module('myAppNavbarDirective', []).directive('navDir', ['', function(){
  // Runs during compile
  return {
      template: 'test if the dir is working'
  };
}]);

模块

var app = angular.module("myApp",   [
                                    'ui.bootstrap',
                                    'ngAnimate',
                                    'myAppRouter',
                                    'myAppHomeCtrl',
                                    'myAppHomeService',
                                    'myAppNavbarDirective'
                                ]);

索引(sn-p)

<!-- Navigation Bar-->
<nav-dir></nav-dir>
<!-- some code -->
<!-- Angular Modules -->
<script type="text/javascript" src="app/app.module.js"></script>
<script type="text/javascript" src="app/app.routes.js"></script>
<script type="text/javascript" src="app/components/home/homeCtrl.js"></script>
<script type="text/javascript" src="app/components/home/homeService.js"></script>
<script type="text/javascript" src="app/shared/navigation-bar/navbarDirective.js"></script>

问题

如您所见,我创建了一个带有指令的模块,然后将该模块放入我的主模块脚本中,并在我的 index.html 中调用它。为什么我会收到这个错误,也许我错过了一些我看不到的东西?

【问题讨论】:

    标签: angularjs angularjs-directive


    【解决方案1】:

    您的错误是因为您试图将名称为 ''(空字符串)的服务注入到您的指令中。

    应该是(去掉空字符串注入)

    angular.module('myAppNavbarDirective', []).directive('navDir', [function(){
      // Runs during compile
      return {
          restrict: 'E',
          template: 'test if the dir is working'
      };
    }]);
    

    【讨论】:

    • 太棒了。谢谢。不仔细检查智能是我的问题哈哈。很棒的收获!
    猜你喜欢
    • 2017-05-16
    • 1970-01-01
    • 2021-11-28
    • 1970-01-01
    • 1970-01-01
    • 2019-07-05
    • 2017-06-27
    • 2020-04-24
    • 1970-01-01
    相关资源
    最近更新 更多