2015-04-14 136 views
0

我有一個名爲profile.html的可重用模板。它看起來是這樣的:AngularJS元素的子範圍

<div> 
    {{firstName}} 

</div> 

我把它嵌入在這勢必專用控制器另一個模板:

<div ng-include src="'templates/profile.html'"></div> 

我要爲這個div創建一個子$範圍。在控制器父模板,我有這樣的:

$scope.profile = theProfile; 

我想爲profile.html模板子範圍是父$ scope.profile。類似於:

<div ng-include src="'templates/profile.html'" ng-scope="{{profile}}"></div> 

我該怎麼做?

+1

爲什麼不直接寫'{{profile.firstName}}'? – floribon

+0

您無法將任意對象轉換爲範圍。 –

回答

1

看起來你基本上是在重新設計指令,試圖設置模板和範圍。另外,$ scope是一個包含大量其他屬性/對象的對象,因此將它設置爲另一個對象會是......有問題的。

如果你確實想這樣做,下面將創建一個指令,使用角度副本將傳入的profile合併到$scope。不過,我建議只使用$ scope.profile。

.directive('profile', [function(){ 
    return{ 
     templateUrl:'templates/profile.html', 
     scope:{profile:'='}, 
     controller: function($scope){ 
      angular.copy($scope.profile, $scope) // if you really, really want the properties right on the scope. 

     } 
    } 
}] 
+0

這似乎緊密耦合,ng-includes profile.html的每個地方都必須在其控制器上有一個屬性「配置文件」,不是嗎? – Jeff

+0

的確,這就是爲什麼指令是一個更好的解決方案。一般來說,我發現ng-include很少用,主要是爲了解決遞歸指令問題。如果你想要一個既具有模板又具有與其關聯的範圍的「配置文件」組件,這正是指令旨在解決的問題。 –

1

ngInclude自動創建子範圍。您不需要顯式傳遞一些數據,因爲它可以通過原型繼承來訪問其父範圍(如果您的模板更改範圍,這可能會成爲問題)。

這裏的問題是您的模板期望firstName屬性存在於範圍內,但它不。所以,你可以你的模板改變

<div> 
    {{profile.firstName}} 
</div> 

但會夫婦將模板profile對象,這可能是一個壞主意。

另一個解決方案是手動創建在正確的範圍firstName屬性:

<div ng-include src="'templates/profile.html'" 
    ng-init="firstName=profile.firstName"> 
</div> 

我不是很喜歡這個解決方案,不過,因爲它可以很容易,如果模板需要失控更多的屬性,並在一定程度上打破了模板封裝。

最後,你可以換一個指令內的模板:

directive('whateverMakesSense', function() { 
    return { 
     restrict: 'E', 
     template: '<div>{{data.firstName}}</div>', 
     scope: { data: '=' }   
    }; 
}); 

... 

<whatever-makes-sense data="profile"></whatever-makes-sense> 

如果你發現自己使用該模板在很多地方,我建議你去自定義指令的方式。它會給你更多的控制權,事情會被更好的封裝,並且作爲獎勵,你的標記語言會更加語義化 - 當然,如果你使用任何其他的東西,除了whatever-makes-sense。 :)