Dan P Dan P - 6 months ago 10
Javascript Question

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.

Answer

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