2015-07-20 109 views
0

我想知道 - 如何使用動態模板製作Directive。 的關鍵是 - 當我的主網頁和主要類別,如page1page2我的模板應該有所有divsAngularJS - 使用動態模板的指令

當我像subpage1subpage2我想有隻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來實現它嗎?

回答

1

*注:我個人更喜歡有一個單獨的文件模板(使用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文件

See other Stackoverflow answer

或Plunkr直接

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" 
    }; 
} 
}; 
}]); 
+0

感謝您的幫助,但 - 我更新了我的Plunkr和您的解決方案(基於ng-if)不起作用:( –

+0

是的它確實:http:/ /plnkr.co/edit/n85cDv7zoB51LrPWeiYo?p=preview – rmuller

+0

噢,我在代碼中犯了一個錯誤,對不起。 最後一個問題 - 如果我只想在子頁面中顯示一個頭文件? –

1

爲什麼作爲rmuller說不能做,並使用templateURL,但你可以在參數傳遞和返回正確的模板例子

templateUrl: function (elem, attrs) { 
       if (attrs.isMain === 'mainPage') { 
        return 'main_view.html'; 
       } 
       return 'other_view.html'; 
      }, 

所以你會分開你的模板我nto文件。我認爲這將是我個人認爲最好的方式

+0

是的,我正在嘗試templateUrl,但現在我正在測試簡單的'模板'。也感謝你的幫助! –