Dan P
Dan P

Reputation: 1999

Using Two Controllers in a Single AngularJS App

Full source code can be found http://plnkr.co/edit/rQSg5eMhm9uc9dSWnWEU?p=preview

In the index.html file if I use only one controller at a time it works. That is if I use

<body>
    <div id="inputExample" ng-app="AngularJSTestBedWebApp" ng-controller="AngularJSInputExampleController">
        input example: <input type="text" ng-model="inputValue" /><br/>
        This is the updated value: {{inputValue}}        
    </div>   
</body>

or if I use

<body>
    <div id="scopeExample" ng-app="AngularJSTestBedWebApp" ng-controller="AngularJSScopeExampleController">
        {{understandingScope}}
    </div> 
</body>

It will also work. However if I use both controllers at the same time such as

<body>
    <div id="scopeExample" ng-app="AngularJSTestBedWebApp" ng-controller="AngularJSScopeExampleController">
        {{understandingScope}}
    </div>

    <div id="inputExample" ng-app="AngularJSTestBedWebApp" ng-controller="AngularJSInputExampleController">
        input example: <input type="text" ng-model="inputValue" /><br/>
        This is the updated value: {{inputValue}}        
    </div>   
</body>

The second controller never gets used. {{inputValue}} never gets assigned a default value and also never updates when you type in the text box. It literally just says "{{inputValue}}" the entire time.

I'm sure this is probably something easy but I'm very new to AngularJS. Thanks in advance for any help.

Upvotes: 2

Views: 47

Answers (2)

merrais
merrais

Reputation: 391

Here a complete example of two applications in one html page and two conrollers in one application :

<div ng-app = "myapp">
  <div  ng-controller = "C1" id="D1">
     <h2>controller 1 in app 1 <span id="titre">{{s1.title}}</span> !</h2>
  </div>

  <div  ng-controller = "C2" id="D2">
     <h2>controller 2 in app 1 <span id="titre">{{s2.valeur}}</span> !</h2>
  </div>
</div>
<script>
    var A1 = angular.module("myapp", [])

    A1.controller("C1", function($scope) {
        $scope.s1 = {};
        $scope.s1.title = "Titre 1";
     });

    A1.controller("C2", function($scope) {
        $scope.s2 = {};
        $scope.s2.valeur = "Valeur 2";
     });
</script>

Upvotes: 0

Mark Coleman
Mark Coleman

Reputation: 40863

The ng-app attribute should be placed at the root of the application. In your example that would be <body/> or <html/>

<body ng-app="AngularJSTestBedWebApp">
    <div id="scopeExample"  ng-controller="AngularJSScopeExampleController">
        {{understandingScope}}
    </div>

    <div id="inputExample" ng-controller="AngularJSInputExampleController">
        input example: <input type="text" ng-model="inputValue" /><br/>
        This is the updated value: {{inputValue}}        
    </div>   
</body>

Updated plnkr

Upvotes: 5

Related Questions