angularjsangularjs-directivemoduleng-controllerng-app

Call multiple modules in a single page?


I created module1 and module2 in a single page. module1 is working fine, module2 is not working. Please suggest how to call module1 and module2 correctly in a single page.

<html xmlns="http://www.w3.org/1999/xhtml">
<head>
    <title></title>
    <script src="http://ajax.googleapis.com/ajax/libs/angularjs/1.4.8/angular.min.js"></script>
    <script>
        var mymodule1 = angular.module('module1', []);

        mymodule1.directive('btnDirective', function() {
            return {
                restrict: 'E',
                template: '<table>' +
                    '<tr><td>Enter a value:<input type="text" ng-model="a" /></td></tr>' +
                    '<tr><td>Enter b Value:<input type="text" ng-model="b" /></td></tr>' +
                    '<tr><td><button ng-click="add(a,b)">Add</button></td></tr>' +
                    '<tr><td>Sum of two number {{sum}}</td></tr>' +
                    '</table>',

                link: function($scope, element, attrs) {

                    $scope.sum = 0;
                    $scope.add = function(a, b) {
                        $scope.sum = parseInt(a) + parseInt(b);
                    }
                }
            };
        });
        var mymodule2 = angular.module('module2', []);

        mymodule2.controller('controller2', function($scope) {
            $scope.name = 'Second Module Controller!';
        });

        angular.bootstrap(document.getElementById("app2"), ['module2']);
    </script>
</head>
<body>
    <h3>Creating Custom Element Directive</h3>
    <br />
    <div ng-app="module1">
        <btn-directive></btn-directive>
    </div>
    <h1>my module2</h1>
    <div id="app2" ng-app="module2" ng-controller="controller2">
        Name: {{name}}
    </div>
</body>
</html>

Solution

  • You use this:

    ng-app="module1"
    

    this involve that your app is module1. You should create a new module (ex: theapp) that require the two modules.

    var app = angular.module('theapp', ['module1', 'module2']);
    

    then replace the ng-app with:

    ng-app='theapp'
    

    then you can have:

    <body ng-app="theapp" ng-controller="controller2">
      <h3>Creating Custom Element Directive</h3><br />
      <div>
        <btn-directive></btn-directive>
        </div>
      <h1>my module2</h1>
      <div>
       Name: {{name}}
        </div>
    </body>