Angularjs – separating directive files, but staying on the same module

All we need is an easy explanation of the problem, so here it is.

I’m trying to separate a directive to another file, without having to declare a new module – not doing:


but just :


the myapp.directives module exists in another file and works fine. but when I try to use it in another file as shown above (without []) it fails.

following this answer It believe my approach should work, but for some reason it fails..

How to solve :

I know you bored from this bug, So we are here to help you! Take a deep breath and look at the explanation of your problem. We have many solutions to this problem, But we recommend you to use the first method because it is tested & true method that will 100% work for you.

Method 1

When you first declare a module it needs to have the dependency argument. Afterwards you can reference that same module using only the module name argument.

/* create module */

/* declare components of same module, note same name*/

If you want to create new modules, you need to inject them in the main ng-app module as dependencies.

/* main ng-app module , injects another module you created below*/

/* new module, must have dependency argument */

Method 2

Wherever it is just refer to the module name (even in different files) and attach the directives.
Javascript will just see what is attached to the module and not see which file it came from.


    .directive('directive1', function () {
        return {


    .directive('directive2', function () {
        return {

Only thing is don’t forget to include both the js files in the view html file.

<script src="file1.js"></script>
<script src="file2.js"></script>

Method 3

You don’t need to chain them together, the link you posted has the answer at the bottom of the question.

In the first file you need to create your app module:

var myApp = angular.module('myApp ', []);

Then in each file you can attach additional things to myApp:

myApp.directive('ngValidate', ['$parse', function ($parse) {

Personally I never chain this stuff together, rather, I put it in separate files.

Note: Use and implement method 1 because this method fully tested our system.
Thank you 🙂

All methods was sourced from or, is licensed under cc by-sa 2.5, cc by-sa 3.0 and cc by-sa 4.0

Leave a Reply