【问题标题】:In AngularJS 1.2, how do I specify the controller for an ng-include?在 AngularJS 1.2 中,如何为 ng-include 指定控制器?
【发布时间】:2013-11-20 13:23:26
【问题描述】:

我们正在尝试从 AngularJS 1.0.7 升级到 1.2.1。在 1.0.7 中,我们能够在同一元素中设置 ng-include 的控制器,就像这样

<div data-ng-include="'include1.html'" data-ng-controller="MyCtrl1"

MyCtrl1 将可用于include1.html 内的代码。

当迁移到我在this plunkr 中说明的 AngularJS 1.2.1 时,这会中断。如果您将引用的版本更改为 1.0.7,则再次 works

我有兴趣了解发生了什么变化/为什么会这样。我尝试搜索但找不到任何东西,或者我没有使用正确的术语。

此外,为我的ng-includes 指定控制器的正确方法是什么?

【问题讨论】:

    标签: javascript angularjs controller


    【解决方案1】:

    为什么不将ng-controller 从具有ng-include 的元素移动到模板内部:

    index.html:

    <div data-ng-include="'include1.html'"></div>    
    <div data-ng-include="'include2.html'"></div>
    

    include1.html

    <div data-ng-controller="MyCtrl1">
        <h1>{{Username}}</h1>
    </div>
    

    include2.html

    <div data-ng-controller="MyCtrl2">
        <h1>{{Username}}</h1>
    </div>
    

    看来ngControllerngInclude 从Angular 1.2 版开始就不能相互结合使用:

    Issue 1Issue 2Issue 3SO post

    【讨论】:

    • 我有兴趣了解为什么会发生这种情况以及发生了什么变化,有什么想法吗?
    • 我认为这与新版本不允许在同一个元素上使用多个指令有关。
    • 我附上了几个链接。
    • 太棒了,我确实看到了 Igor Minar 的帖子,但略过了。感谢您指出正确的地方!
    • 我注意到 ng-include 创建了子范围。这种方法是否意味着您创建了一个孙子范围?
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2017-09-27
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-09-17
    相关资源
    最近更新 更多