Pav*_*nin 5 angularjs angularjs-ng-include
我打算在具有不同控制器的多个视图中使用一个模板.
但是现在我意识到我不能只在模板中编写通用绑定,因为值会放在里面$scope.concreteControllerName.
ngInclude的 Angular文档说明了这一点
该指令创建新范围.
我可以使用ng-init指令并将控制器实例传递给模板的范围:
<ng-include src="..." ng-init="controller=concreteControllerName"/>
Run Code Online (Sandbox Code Playgroud)
甚至更好
<ng-include src="..." ng-init="model=getModelForTemplate()"/>
Run Code Online (Sandbox Code Playgroud)
然后写入{{controller.boundvalue}}模板.
我猜这是一个有效的解决方案.
在这里,我想知道是否存在其他更好的方法,如果不存在,模板是否应该与传递模型的一些概念一起使用以从父范围中抽象出来?
使用 John Papa 的controllerAs View Syntax和controllerAs 与 vm。您在指令中指定不同的控制器ng-include,但使用相同的 src html 模板。vm模板中使用公共变量名称。
索引.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>
Run Code Online (Sandbox Code Playgroud)
控制器One.js
function controllerOne() {
var vm = this;
vm.name = 'Controller One!';
Run Code Online (Sandbox Code Playgroud)
共享模板.html
<div>{{vm.name}}</div>
Run Code Online (Sandbox Code Playgroud)
这是完整的工作版本:Plunker 中的完整工作代码
| 归档时间: |
|
| 查看次数: |
2290 次 |
| 最近记录: |