我在我的应用程序中使用 ng-include 。它有效,但我想知道这是否是执行 ng-include 的好方法。 ng-include 文件内的 html 正在从其父级调用该函数。
这个例子可以在这个plunkr中看到。 。 plunkr 不显示按钮,但其想法是 ng-include 文件中的元素正在调用其父函数。这是不好的做法吗?有替代方案吗? 例如,我的 ng-include 中的 html 包含以下内容:
<button class="mybutton" ng-click="ctrl.parentFn"></button>
我问的原因是因为我有一个指令,其中有一个带有按钮的默认模板。如果用户想要指定自定义模板(例如按钮的不同位置或更多元素),他们可以指定自定义模板,但允许他们使用其父 Controller 的默认功能(ng-click)。
任何评论都非常受欢迎和赞赏。
最佳答案
我无法争论这一点,但如果你的 div 嵌套在多个 Controller 中,那么你需要使用 $parent.$parent.$parent
,根据 Controller 层次结构,它可以增加长度。
所以我建议您使用controllerAs语法,它提供 Controller 的别名,并且可以通过使用可以访问其方法的任何 Controller 的别名在任何div内访问它。
标记
<div ng-controller="MainCtrl as main">
{{ main.title }}
<div ng-controller="AnotherCtrl as another">
{{ another.title }}
<div ng-controller="YetAnotherCtrl as yet">
{{ yet.title }}
</div>
</div>
</div>
引用this article了解更多详细信息。
关于angularjs - 在 ng-include 中调用父函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29970562/