我打算在具有不同控制器的多个视图中使用一个模板.
但现在我意识到我不能只在模板中编写通用绑定,因为值将放在$scope.concreteControllerName中.
ngInclude的Angular docs说
This directive creates new scope.
我可以使用ng-init指令并将控制器实例传递给模板的作用域:
<ng-include src="..." ng-init="controller=concreteControllerName"/>
甚至更好
<ng-include src="..." ng-init="model=getModelForTemplate()"/>
然后在模板中编写{{controller.boundvalue}}.
我猜这是一个有效的解决方案.
在这里,我想知道是否存在其他更好的方法,如果不存在,模板是否应该与传递模型的一些概念一起使用以从父范围中抽象出来?
使用John Papa的
controllerAs View Syntax和
controllerAs 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