[英]AngularJS - directive with dynamic template
我想知道-如何使用動態模板制定Directive
。 關鍵是-當我進入主頁和主要類別(如page1
或page2
我的模板應具有所有divs
當我進入subpage1
或subpage2
類的子菜單時,我只希望有3 divs
。 如何動態實現呢? 我知道我必須在每個子頁面上使用指令
<my-template whereIam="page1"></my-template>
或<my-template whereIam="subpage2"></my-template>
但是我做不到。 你可以幫幫我嗎?
我的指令與示例模板:
angular.module('dynamic-template').directive('myTemplate', function () {
return {
restrict: 'E',
template: "<div1> "
+ "<h1> Main pages and subpages </h1>"
+ "</div1>"
+ "<div2>"
+ "<h2> Main pages and subpages </h2>"
+ "</div2>"
+ "<div3>"
+ "<h3> Main pages and subpages </h3>"
+ "</div3>"
+ "<div4>"
+ "<h4> Only mainpages </h4>"
+ "</div4>"
+ "<div5>"
+ "<h5> Only subpages </h5>"
+ "</div5>"
};
}]);
頁面之一上的HTML:
<my-template whereIam="??" ></menu-template>
例子Plunkr
http://plnkr.co/edit/kVk3mJWUbTqhFEHVUjt1?p=preview
我已經搜索過了,但是迷路了:(
我是否使用$ compile來實現它?
*注意:就個人而言,我更喜歡將模板放在單獨的文件中(使用templateUrl)
但是...
您可以傳遞頁面的頁面類型並使用ng-if。
angular.module('dynamic-template').directive('myTemplate', function () {
return {
restrict: 'E',
scope: { isMain: "=main"},
template: "<div1> "
+ "<h1> Main pages and subpages </h1>"
+ "</div1>"
+ "<div2>"
+ "<h2> Main pages and subpages </h2>"
+ "</div2>"
+ "<div3>"
+ "<h3> Main pages and subpages </h3>"
+ "</div3>"
+ "<span ng-if='isMainPage'><div4>"
+ "<h4> Only mainpages </h4>"
+ "</div4>"
+ "<div5>"
+ "<h5> Only mainpages </h5>"
+ "</div5></span>"
};
}]);
並在您的html中(當它是主頁時)
<my-template main="true"/>
否則,我對類似問題的回答可能對您有用:
這樣做確實需要您為每個文件創建單獨的html文件
或直接使用Plunkr
app.directive('myDirective', [function(){
return {
template: '<div ng-include="getTemplate()"></div>',
restrict: 'E',
scope: {template: '='},
link: function(scope, element, attr, ctrl) {
var baseURL = 'templates/myDirective.'
scope.getTemplate = function(){
baseURL = "" //remove this
return baseURL + scope.template + ".html"
};
}
};
}]);
為什么不按照rmuller所說的那樣使用並使用templateURL,但是您可以傳入參數並返回正確的模板示例
templateUrl: function (elem, attrs) {
if (attrs.isMain === 'mainPage') {
return 'main_view.html';
}
return 'other_view.html';
},
因此,您可以將模板分成文件。 我認為這將是最好的方法
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.