angularjs - 在 ng-include 中调用父函数

标签 angularjs angularjs-ng-include

我在我的应用程序中使用 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/

相关文章:

javascript - 指令在其子项之前初始化

javascript - AngularJS - 将 $index 显示为 char

c# - DbContext 在使用异步任务方法时被处置

angularjs - 使用 nginclude 时避免使用额外的 DOM 节点

html - 为什么 AngularJS ng-view 在本地不起作用?

javascript - Angular JS : include partial HTML inside another ng-include

javascript - 如何从url中读取angularjs中的完整查询字符串?

angularjs - mattlewis92/angular-bootstrap-calendar 在不同时区计算错误日期

caching - 如何以 Angular 检查特定网址是否已在 $templateCache 中

javascript - ng-include 中的指令