在单个AngularJS应用程序中使用两个控制器

Dan*_*n P 2 javascript angularjs

可以找到完整的源代码http://plnkr.co/edit/rQSg5eMhm9uc9dSWnWEU?p=preview

在index.html文件中,如果我一次只使用一个控制器,它就可以工作.那是我使用的

<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>
Run Code Online (Sandbox Code Playgroud)

或者如果我使用

<body>
    <div id="scopeExample" ng-app="AngularJSTestBedWebApp" ng-controller="AngularJSScopeExampleController">
        {{understandingScope}}
    </div> 
</body>
Run Code Online (Sandbox Code Playgroud)

它也会奏效.但是,如果我同时使用两个控制器,如

<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>
Run Code Online (Sandbox Code Playgroud)

第二个控制器永远不会被使用.永远不会为{{inputValue}}分配默认值,也不会在文本框中输入时更新.它实际上只是说"{{inputValue}}".

我敢肯定这可能很容易,但我对AngularJS很新.在此先感谢您的帮助.

Mar*_*man 5

ng-app属性应放在应用程序的根目录下.在你的例子中将是<body/><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>
Run Code Online (Sandbox Code Playgroud)

更新了plnkr