2014-10-17 80 views
5

我打算在具有不同控制器的多個視圖中使用一個模板。
在ControllerAs語法中使用ngInclude的最佳實踐是什麼?

但現在我意識到我不能在模板中編寫通用綁定,因爲值將被放在$scope.concreteControllerName之內。

ngInclude角文檔說

此指令創建新的範圍。

我可以用ng-init指令,並通過控制器實例模板的範圍:

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

甚至更​​好

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

,然後在模板寫{{controller.boundvalue}}

這是一個工作解決方案,我猜。

在這裏我想知道是否有其他更好的方法存在,如果不是,應該使用模板總是與傳遞模型的一些概念來抽象遠離父範圍?

+1

看看這個[SO問題](http://stackoverflow.com/questions/13422966/how-to-specify-model-to-a-nginclude-directive- in-angularjs/20639139#20639139) - 幾個答案都很棒。 – 2014-10-17 15:28:19

回答

3

使用約翰帕帕的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

+0

在你的Plunker中,顯示你如何從子控制器引用父控制器(不使用$ scope)會很好。 – 2017-02-06 12:40:52

相關問題