我在想是否有办法通过AngularJS中templateUrl中的directive合并部分视图?

假设我有指令:

.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?
    };
});


我将再提供一些局部片段,并且在某些情况下会对其进行修正(例如:

mainpartial与partial2,partial4,partial6的一种视图

结合了mainpartial与partial1和partial5的另一个视图)

我想知道这种方式,因为我的部分文件有很多HTML代码,因此我可以将它们放入template而不是templateUrl,但是会有大量的代码。我想避免这种情况。

AngularJS中可能吗?

最佳答案

只需ng-include mainpartial.html中的所有部分:

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


确保将部分网址分配给$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>


请注意,我包括了额外的引号,因此angular将属性解释为字符串。

08-19 23:35