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

标签 javascript angularjs angularjs-scope

在 AngularJS 中,是否可以从包含的部分中继承父 Controller 的范围,而不是通过注入(inject)的服务传递数据?

案例:

假设 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>

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

最佳答案

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

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

See the docs on Scope.

Here是一个例子 plunker。

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

关于javascript - 在没有服务的情况下从 ng-include 继承外部 Controller 的范围?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28305031/

相关文章:

javascript - 如何使用 JavaScript 搜索 JSON 树

javascript - Angular、karma/jasmine 测试不处理 .bind

jQuery 和 AngularJS : Bind Events to Changing DOM

javascript - selectboxit 的 AngularJs 问题

javascript - 为什么两个$scopes同时更新,重复数据

javascript - 用鼠标移动 Canvas 形状

javascript - 通过卡住浏览器同步加载图像

angularjs - 如果表单控件具有无效数据,$setPristine() 将无法正常工作

javascript - Meteor Angular & Request - 如何绑定(bind)?

javascript - 使用 .map 将数量转换为百分比