2013-06-12 43 views
14

因此,對於Angular 1.1.4,您可以擁有一個動態模板url。 hereDynamic templateUrl - AngularJS

templateUrl - 與模板相同,但模板從指定的URL加載。由於模板加載是異步的,編譯/鏈接將暫停,直到加載模板。

您可以指定templateUrl作爲表示URL的字符串,或者作爲一個函數,它接受兩個參數tElement和tAttrs(在下面的編譯函數api中描述)並返回表示url的字符串值。

我該如何利用這個來生成一個動態模板,這個模板基於我的指令上的一個屬性?顯然,這是不行的,因爲tAttrs.templateType簡直是字符串「templateType」

templateUrl: function (tElement, tAttrs) { 
    if (tAttrs.templateType == 'search') { 
    return '/b/js/vendor/angular-ui/template/typeahead/typeahead.html' 
    } else { 
    return '/b/js/vendor/angular-ui/template/typeahead/typeahead2.html' 
    } 
} 

由於我沒有訪問的範圍,我該如何管理呢?

+0

作爲角1.2.17的(甚至更早),你最初的想法似乎工作。 –

回答

26

下也有可能在AngularJS創建動態模板: 在你的指令使用:

template : '<div ng-include="getTemplateUrl()"></div>' 

現在您的控制器可以決定使用哪個模板:

$scope.getTemplateUrl = function() { 
    return '/template/angular/search'; 
}; 

因爲你有acc可以這樣做:

$scope.getTemplateUrl = function() { 
    return '/template/angular/search/' + $scope.query; 
}; 

因此,您的服務器可以爲您創建一個動態模板。

+14

雖然這很有趣,但是它似乎違背了角度設計的理念,因爲它引入了僞指令和控制器之間的依賴關係,這會削弱僞指令的封裝和獨立功能。 – Jarnal

+1

您可以在指令中的'link:'屬性內部聲明/分配動態函數,因爲鏈接可以接受一個回調函數(scope,element,attrs)'來提供對'scope'的訪問。這提高了它獨立的能力。 – cjn

1

所以問題在於我如何入侵typeahead指令......我在typeahead上設置了一個scope變量,在typeaheadPopup指令上進行評估。相反,我只是直接通過templateType attr,因爲字符串&對此進行了評估。例如。

var popUpEl = angular.element(
    "<typeahead-popup " + 
    "matches='matches' " + 
    "active='activeIdx' " + 
    "select='select(activeIdx)' " + 
    "template-type='" + attrs.templateType + "'" + 
    "query='query' " + 
    "position='position'>" + 
    "</typeahead-popup>"); 

而不是"template-type='templateType'"

1

爲不支持File API的瀏覽器(< IE10)創建文件上傳回退時出現類似問題。關鍵的區別在於我需要頁面智能地決定顯示哪個模板,而無需打開屬性值的好處。

我最終爲我的指令使用constant供應商。常量基本上設置了默認參數,可以在指令中的任何位置注入。我只是讓常量調用一個函數來確定瀏覽器支持,然後在需要確定要拖動哪個模板時引用該值。這是很好的,因爲1)有沒有屬性可供參考和2)它是在預連接階段,當你無法訪問控制器時可用。

(function() { 
    var myDir = angular.module('myDir', []); 
    myDir.constant('myDirConfig', { 
     hasFileSupport: fileApiIsSupported() 
    }); 

    myDir.directive('myDir', ['myDirConfig', function (myDirConfig) { 
     return { 
      templateUrl: function() { 
       if (myDirConfig.hasFileSupport) { 
        return 'pathToTemplate/html5.html'; 
       } else { 
        return 'pathToTemplate/fallback.html'; 
       } 
      } 
     }; 
    }]; 

    function fileApiIsSupported() { return (...); } 
})(); 
3
templateUrl: function (elem, attrs) { 
return attrs["template"] == "table" ? 
"tableTemplate.html" : "itemTemplate.html"; 
} 
+5

儘管此代碼可能會回答問題,但提供有關此代碼爲何和/或如何回答問題的其他上下文可提高其長期價值。 – ryanyuyu