在 ng-include 中调用父函数



我在我的应用程序中使用了ng-include。它正在工作,但我想知道这是否是执行 ng-include 的好方法。ng-include 文件中的 html 正在从其父级调用函数。

这个例子可以在这个 plunkr 中看到。plunkr 没有显示按钮,但想法是 ng-include 文件中的元素正在调用其父函数。这是不好的做法吗?有没有其他选择?例如,我的 ng-include 中的 html 包含以下内容:

  <button class="mybutton" ng-click="ctrl.parentFn"></button>

我问的原因是因为我有一个指令,其中有一个带有按钮的默认模板。如果用户想要指定自定义模板(如按钮的不同位置或更多元素),他们可以指定自定义模板,但允许他们使用其父控制器的默认功能(ng-click)。

任何评论都非常欢迎和赞赏。

我不能争论这一点,但是如果你的div嵌套在几个控制器中,那么你需要使用$parent.$parent.$parent,根据控制器层次结构,它可以增加长度。

所以我建议你使用提供控制器别名的controllerAs语法,它可以通过使用任何控制器的别名在任何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>

有关更多详细信息,请参阅此文章

最新更新