使用带有ControllerAs语法的ngInclude的最佳实践是什么?

时间:2014-10-17 15:05:01

标签: angularjs angularjs-ng-include

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

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

ngInclude的Angular文档说

  

该指令创建新范围。

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

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

甚至更好

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

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

我猜这是一个有效的解决方案。

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

1 个答案:

答案 0 :(得分:3)

使用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

相关问题