gpt4 book ai didi

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

转载 作者:数据小太阳 更新时间:2023-10-29 04:15:50 24 4
gpt4 key购买 nike

在 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/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com