2015-08-13 23 views
0

我在想,是否有辦法在AngularJS的directive中通過templateUrl合併部分視圖?如何通過templateUrl合併幾個偏角AngularJS

比方說,我有指令:

.directive('mergeThisStupidPartials', function() { 
    var mainpartial = "mainpartial.html", 
    var template2 = "partial2.html", 
    var template3 = "partial3.html" 

    return { 
     restrict: "E", 
     templateUrl: mainpartial, 

     //merge mainpartial with template2 and template3 
     //link function need? 
    }; 
}); 

我會有一些更多的諧音,他們會在某些情況下(被renered例如:

與mainpartial與partial2,partial4,partial6

一個視圖

與partial1和partial5

組合mainpartial另一視圖

我想知道這種方式,因爲我的部分有很多HTML代碼,我可以將它們放入template,而不是templateUrl,但隨後會出現一大塊代碼。我想避免這種情況。

AngularJS有可能嗎?

回答

1

mainpartial.html只是ng-include所有的諧音:

<div ng-include="template1"></div> 
<div ng-include="template2"></div> 
<div ng-include="template3"></div> 
<!-- etc --> 

確保分配部分的URL $scope變量:

.directive('mergeThisStupidPartials', function() { 
    var mainpartial = "mainpartial.html"; 

    return { 
     restrict: "E", 
     templateUrl: mainpartial, 
     controller: ['$scope', function ($scope) { 
      $scope.template1 = "partial1.html"; 
      $scope.template2 = "partial2.html"; 
      $scope.template3 = "partial3.html"; 
      // Etc 
     }] 
    }; 
}]); 

您也可以直接在mainpartial.html使用路徑:

<div ng-include="'partial1.html'"></div> 
<div ng-include="'partial2.html'"></div> 
<div ng-include="'partial3.html'"></div> 

請注意,我包括d額外的引號,所以角度將這些屬性解釋爲字符串。

+0

'$ scope' in directive? –

+0

是的,忘了包括它,編輯... – Cerbrus

+0

我不知道我可以注入$範圍到指令,Angular拋出一個錯誤'未知的提供者:$ scopeProvider < - $ scope' –