Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

like image 939
KishanCS Avatar asked Jan 04 '23 14:01

KishanCS


2 Answers

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

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

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

like image 92
a.u.b Avatar answered Jan 07 '23 03:01

a.u.b


only one AngularJS application can be auto-bootstrapped per HTML document. The first ngApp found in the document will be used to define the root element to auto-bootstrap as an application. To run multiple applications in an HTML document you must manually bootstrap them using angular.bootstrap instead.

From https://docs.angularjs.org/api/ng/directive/ngApp

You have two ng-app in your example, put both controllers in the same module (for example myApp) and you'll be fine

like image 45
Rui Avatar answered Jan 07 '23 02:01

Rui