Search code examples
javascripthtmlangularjsangular-controller

Angular JS only one controller working when i used multiple controllers in a single page


Problem in handling two controller As am a learner to angular Js this is where i got my confusion

I wrote two with two different apps and controllers and apps as I have learnt we can define multiple of these in a single page.

The first part div which is

<div ng-app="myApp" ng-controller="personCtrl">

    First Name: <input type="text" ng-model="firstName"><br>
    Last Name: <input type="text" ng-model="lastName"><br>
    <br>
    Full Name: {{fullName()}}

</div>

worked well 

enter image description here When I used with two controllers like this

<html>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.4.8/angular.min.js"></script>
<body>

<div ng-app="myApp" ng-controller="personCtrl">

First Name: <input type="text" ng-model="firstName"><br>
Last Name: <input type="text" ng-model="lastName"><br>
<br>
Full Name: {{fullName()}}

</div>

<br><br>


<div ng-app="myApp1" ng-controller="personCtrl1">

First Name: <input type="text" ng-model="firstName"><br>
Last Name: <input type="text" ng-model="lastName"><br>
<br>
Full Name: {{fullName()}}

</div>


<script>
var app = angular.module('myApp', []);
app.controller('personCtrl', function($scope) {
    $scope.firstName = "John";
    $scope.lastName = "Doe";
    $scope.fullName = function() {
        return $scope.firstName + " " + $scope.lastName;
    };
});
var app1 = angular.module('myApp1', []);
app1.controller('personCtrl1', function($scope) {
    $scope.firstName = "John";
    $scope.lastName = "Doe";
    $scope.fullName = function() {
        return $scope.firstName + " " + $scope.lastName;
    };
});
</script>

</body>
</html>

This is what the problem is

enter image description here


Solution

  • Give an id to your second div and add this line:

    angular.bootstrap(document.getElementById("myApp1"), ['myApp1']);
    

    http://jsfiddle.net/ADukg/9952/