【问题标题】:What are the best practices of using ngInclude with ControllerAs syntax?将 ngInclude 与 ControllerAs 语法结合使用的最佳实践是什么?
【发布时间】:2014-12-13 05:02:33
【问题描述】:

我打算在具有不同控制器的多个视图中使用一个模板。

但现在我意识到我不能只在模板中编写通用绑定,因为值将放在 $scope.concreteControllerName 中。

ngInclude 的 Angular 文档这样说

此指令创建新范围。

我可以使用ng-init 指令并将控制器实例传递给模板的范围:

<ng-include src="..." ng-init="controller=concreteControllerName"/> 

甚至更好

<ng-include src="..." ng-init="model=getModelForTemplate()"/>

然后在模板中写入{{controller.boundvalue}}

我猜这是一个可行的解决方案。

在这里我想知道是否存在其他更好的方法,如果没有,是否应该始终将模板与传递模型的概念一起使用以从父范围抽象出来?

【问题讨论】:

标签: angularjs angularjs-ng-include


【解决方案1】:

使用 John Papa 的 controllerAs View SyntaxcontrollerAs with vm。您在 ng-include 指令中指定不同的控制器,但使用相同的 src html 模板。模板中使用了常见的vm变量名。

index.html

<div ng-include ng-controller="controllerOne as vm" src="'same.html'"></div>
<div ng-include ng-controller="controllerTwo as vm" src="'same.html'"></div>
<div ng-include ng-controller="controllerThree as vm" src="'same.html'"></div>

controllerOne.js

function controllerOne() {
    var vm = this;
    vm.name = 'Controller One!';

sharedTemplate.html

<div>{{vm.name}}</div>

这是一个完整的工作版本:Full Working Code in Plunker

【讨论】:

  • 最好在你的 Plunker 中展示你如何从子控制器引用父控制器(不使用 $scope)。
猜你喜欢
  • 2010-10-29
  • 2010-09-06
  • 2013-08-11
  • 2013-08-20
  • 2010-11-28
  • 2020-11-03
  • 2018-06-22
  • 2018-03-13
  • 1970-01-01
相关资源
最近更新 更多