Ajai Krishnan R
Ajai Krishnan R

Reputation: 135

Is there any way to use two ng-app's like parent and clild app in AngularJs?

HTML

chech out the below sample html, I require something like this.

<div id="parentApp" ng-app="parentApp" ng-cloak="" ng-controller="mainController">
    <div id="someContent">
        {{$scope.parentName}}
        ***some parent app actions***
    </div>
    <div id="childApp" ng-app="childApp">
        <div id="someContent" ng-controller="secondController">
            {{$scope.childName}}
            ***some child app actions***
        </div>
    </div>
</div>

Script

2 simple app and controllers for better understanding purpose.

var parentApp = angular.module('parentApp', []);
parentApp.controller('mainController', function($scope, $http) {
    $scope.parentName = 'Parent!!'
});

var childApp = angular.module('childApp', []);
childApp.controller('secondController', function($scope, $http) {
    $scope.childName = 'Child!!'
});

Upvotes: 0

Views: 48

Answers (2)

Mike Feltman
Mike Feltman

Reputation: 5176

If you already have two separate apps and are trying to leverage parts of one in another app, you can inject the module from one app into another. It's the the same structure as you've outlined above, but it will make everything from the first app available in the second app.

angular.module('childApp', ['parentApp'])...

Upvotes: 0

Gautam Sheth
Gautam Sheth

Reputation: 2490

You cannot use 2 ng-app attribute on a page.

However, looking at your requirement, I think you need to use 2 controllers and do some stuff with it while maintaining the appearance of parent-child in the HTML structure. To, do that you can make use of the angular.bootstrap method.

So, you can modify the html as below:

<div id="parentApp" ng-cloak="" ng-controller="mainController">
    <div id="someContent">
        {{$scope.parentName}}
        ***some parent app actions***
    </div>
    <div id="childApp" ng-app="childApp">
        <div id="someContent" ng-controller="secondController">
            {{$scope.childName}}
            ***some child app actions***
        </div>
    </div>
</div>

And in your code, you can initialize it as below:

var parentAppDivId = document.getElementById('parentApp');
angular.bootstrap(parentAppDivId, ['parentApp']);
var parentApp = angular.module('parentApp', []);
parentApp.controller('mainController', function($scope, $http) {
    $scope.parentName = 'Parent!!'
});

var childAppDivId = document.getElementById('childApp');
angular.bootstrap(childAppDivId, ['childApp']);
var childApp = angular.module('childApp', []);
childApp.controller('secondController', function($scope, $http) {
    $scope.childName = 'Child!!'
});

Upvotes: 1

Related Questions