Angularjs - 分离指令文件,但保留在同一模块上

alo*_*ser 24 angularjs angularjs-directive

我正在尝试将指令分离到另一个文件,而不必声明一个新模块 - 没有做:

 angular.module('myapp.newmodule',[]).directive
Run Code Online (Sandbox Code Playgroud)

只是 :

angular.module( 'myapp.directives')指令( ''

myapp.directives模块存在于另一个文件中并且工作正常.但是当我尝试在另一个文件中使用它时,如上所示(没有[])它失败了.

按照这个答案它相信我的方法应该工作,但由于某种原因,它失败了..

cha*_*tfl 21

当您第一次声明模块时,它需要具有依赖项参数.之后,您可以仅使用模块名称参数引用同一模块.

/* create module */
angular.module('myapp.newmodule',['ngRoute','ngResource']);

/* declare components of same module, note same name*/
angular.module('myapp.newmodule').directive....
Run Code Online (Sandbox Code Playgroud)

如果要创建新模块,则需要将它们ng-app作为依赖项注入主模块中.

/* main ng-app module , injects another module you created below*/
angular.module('myapp.newmodule',['ngRoute','ngResource','myUploader']);

/* new module, must have dependency argument */
angular.module('myUploader',[]).directive...
Run Code Online (Sandbox Code Playgroud)


Har*_*nam 13

无论何处它只是引用模块名称(即使在不同的文件中)并附加指令.Javascript只会看到附加到模块的内容,而不会看到它来自哪个文件.

file1.js

angular.module('module-name')
    .directive('directive1', function () {
        return {
            ....
        };
    });
Run Code Online (Sandbox Code Playgroud)

file2.js

angular.module('module-name')
    .directive('directive2', function () {
        return {
            ....
        };
    });
Run Code Online (Sandbox Code Playgroud)

唯一不要忘记在视图html文件中包含两个js文件.说index.html

<script src="file1.js"></script>
<script src="file2.js"></script>
Run Code Online (Sandbox Code Playgroud)

  • 这有效!但请注意,您只在一个文件(主应用程序文件)file1中使用括号作为依赖项:angular.module('module-name',[])... file2:angular.module('module-name')..否则它不起作用. (3认同)

Phi*_*ill 5

您不需要将它们链接在一起,您发布的链接在问题的底部有答案.

在第一个文件中,您需要创建应用程序模块:

var myApp = angular.module('myApp ', []);
Run Code Online (Sandbox Code Playgroud)

然后在每个文件中,您可以附加其他内容myApp:

myApp.directive('ngValidate', ['$parse', function ($parse) {
  ....
}]);
Run Code Online (Sandbox Code Playgroud)

就个人而言,我从不把这些东西连在一起,而是将它放在单独的文件中.