Sunday, June 2, 2024
 Popular · Latest · Hot · Upcoming
95
rated 0 times [  97] [ 2]  / answers: 1 / hits: 21848  / 11 Years ago, tue, october 29, 2013, 12:00:00

I want to be able to use multiple ng-app={angular.module} directives on one page. I want to do this to make the bits of my app more modular. I figure, if I can create angular modules and plug several of them into one document, I could take those modules and plug them into other projects easily.



I have seen people say that you can only use one ng-app directive on your page... is this true? Is it most accurate to say, one ng-app directive per view?



I hope this is not the case, or if it is the case that there is still a best way to achieve a high degree of abstract modularity.



Here are my modules/apps and their controllers...



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


var controllers = {};

controllers.SearchList = function ($scope){

$scope.coworkers = [
{name: 'Joe Bob', city: 'Ukrainia'},
{name: 'Adam Blobnovski', city: 'Logan' },
{name: 'Carlos Sanchez', city: 'Deerbushle'},
{name: 'Martin Kellerweller', city: 'Uptown'},
{name: 'John Doe', city: 'New York City'}
];
};

searchModj.controller(controllers);



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



controllers.SomeFruit = function ($scope) {

$scope.fruits = ['apple', 'banana', 'pear'];

};

fruitModj.controller(controllers);


Ok, now here is the relevant part of my markup...



<div ng-app=searchModule>

<div ng-controller=SearchList>

Name:
<br/>
<input type=text ng-model=name />
<br/>
<ul>
<li ng-repeat=coworker in coworkers | filter:name>{{ coworker.name }} - {{ coworker.city }}</li>
</ul>

<p>You are searching for <em>{{ name }}</em></p>


</div>


</div>

<div ng-app=fruiter>
<div ng-controller=SomeFruit>

<ul>
<li ng-repeat=fruit in fruits>{{ fruits }}</li>
</ul>

</div>

</div>


I think because it comes first in the document, my searchModule app works and the second app does not. When I comment out the first app, the second works. So it looks like I'm confirming my most unfortunate suspicions. Regardless... if this is the case, then what is the best approach I can bear in mind to make the functionality on my projects as modular as possible?


More From » angularjs

 Answers
20

you only want one ng-app on a page, but you can insert your other modules as dependencies of the main ng-app module.



var app=angular.module('myNgAppName', ['searchModule']);


This will expose any directives , controllers etc you have in your 'searchModule'


[#74634] Monday, October 28, 2013, 11 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
tyquandaquanl

Total Points: 122
Total Questions: 109
Total Answers: 101

Location: South Georgia
Member since Sun, Aug 8, 2021
3 Years ago
;