crowhill crowhill - 5 months ago 9
AngularJS Question

Angular directives in two different files: only one will appear in the view

I have two nearly-identical directives in two files.

File one:

//firstTestDirective.js
angular.module('utility', [])
.directive('firstTest', function() {
return {
restrict: 'AE',
template: '<div>first test</div>'
};
});


File two:

//secondTestDirective.js
angular.module('utility', [])
.directive('secondTest', function() {
return {
restrict: 'AE',
template: '<div>second test</div>'
};
});


Both files are included in
index.html
, as well as a pair of tags that call them:

<body>
...
<div first-test></div>
<div second-test></div>
...
</body>
<script src=".../firstTestDirective.js"></script>
<script src=".../secondTestDirective.js"></script>


This should be simple, but here comes the weirdness: the directive in whichever script gets loaded after the other is the only one that appears.

As written above, I get "second test," but not "first test" on my view. If I reverse the load order...

<script src=".../secondTestDirective.js"></script>
<script src=".../firstTestDirective.js"></script>


...then I will get "first test" but not "second test" on my view.

The bug, or whatever it might be, is driving me slightly crazy.

Anyone else ever run into a similar issue?

P.S. A number of other scripts are loaded after the two above scripts and they all seem to work fine. There are no errors in Chrome debug and all scripts are loading.

Answer

While adding other directive you should not recreate a module again, use the module utility defined by 1st js file which is secondTestDirective.js. Basically what happen when you have angular.module('utility', []) in 2nd file it clears out all the registered component with utility module.

angular.module('utility') //used already created module
.directive('firstTest', function() {