在没有服务的情况下从 ng-include 继承外部控制器的范围?

Inherit outer controller's scope from within ng-include without a service?

在 AngularJS 中,是否可以从包含的部分中继承父控制器的作用域,而不是通过注入的服务传递数据?

示例案例:

假设 ParentCtrl 的范围如下:{ testData: 'testing stuff' }

<div ng-controller="ParentCtrl">
    Here we're defined: {{testData}}
    <div ng-include="'partial.html'"></div>
</div>

并在 partial.html 内:

<em>Inherited: {{testData}}</em>

所以局部甚至不需要它自己的控制器。如果这是不可能的,并且您只能通过服务在控制器之间传递注入的数据,为什么 Angular 这样做了?

使用 ngInclude documentation 中的示例 Plunkr,我能够从局部访问父控制器的范围。比如把template1.html的内容改成:

Content of template1.html {{ template }}

根据文档,ngInclude 创建了一个新范围,这意味着您需要遵守 "having a dot in your scope" 的 angular 最佳实践(访问范围内的对象而不是原始对象值),以避免引用损坏的问题。您可以查看 this Stack Overflow question 了解更多信息。

是的,这实际上是默认情况下的工作方式。 ng-include 始终创建一个新范围并且:

A "child scope" (prototypically) inherits properties from its parent scope.

See the docs on Scope.

Here 是一个例子。

编辑: 此外,我刚刚注意到您的原始问题中存在语法问题。模板应该用单引号括起来。将 <div ng-include="partial.html"></div> 更改为 <div ng-include="'partial.html'"></div>