Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

angular.js directives in different modules

Tags:

angularjs

I am confused. If I can use ng-app only once per page how can I use directives that sit in different modules, in different .js files. Look:

<script src='mainModule.js'/>
<script src='secondModule.js'/>
<body ng-app='mainModule'>
   <my-thingy/>
   <div>
      <other-thingy/>
   </div> 
</body>

mainModule.js:
   angular.module("mainModule",[]).directive("myThingy",function(){ ... })

secondModule.js:
   angular.module("secondModule",[]).directive("otherThingy",function(){ ... })

So, how do I now point to the secondModule on the page, without referencing it from mainModule.js

like image 808
iLemming Avatar asked Mar 26 '13 16:03

iLemming


People also ask

Can we use multiple directives in AngularJS?

... is quite illustrative as AngularJS doesn't allow multiple directives (on the same DOM level) to create their own isolate scopes. According to the documentation, this restriction is imposed in order to prevent collision or unsupported configuration of the $scope objects.

Can we have multiple modules in AngularJS?

Yes, you can define multiple modules in angularJS as given below. The modularization in AngularJS helps us to keep the code clarity and easy to understand, as we can combine multiple modules to generate the application.

Which directive is used to load various AngularJS modules in AngularJS application?

The ng-app directive defines the root element of an AngularJS application and starts an AngularJS Application. The ng-app directive will auto-bootstrap (automatically initialize) the application when a web page is loaded. It is also used to load various AngularJS modules in AngularJS Application.


1 Answers

@Agzam, just create a third, top-level, application module that will have dependencies on your sub-modules containing directives:

<script src='mainModule.js'/>
<script src='secondModule.js'/>
<script>
  angular.module('app', ['mainModule', 'secondModule'])
</script>
<body ng-app='app'>
   <my-thingy/>
   <div>
      <other-thingy/>
   </div> 
</body>
like image 55
pkozlowski.opensource Avatar answered Oct 15 '22 13:10

pkozlowski.opensource