2017-10-11 38 views
0

我有三個自定義指令,例如<sample-grid></sample-grid>,<sample-form></sample-form><sample-view></sample-view>。這些都是通過以下方式確定:從控制器動態加載時呈現自定義指令

angular.module("MyApp").directive('sampleGrid', [ function() { 
    return { 
     scope : {}, 
     restrict: 'EA', 
     templateUrl : 'view/templates/sample-grid.tmpl.html', 
     controller : 'SampleGridCtrl', 
     scope: { 
       scnid: '=', 
      } 
    }; 
} ]); 

我在那裏,我在下面的方式使用<md-tabs>angular material主視圖 -

<md-tabs> 
    <md-tab ng-repeat="tab in myCtrl.pageTabs track by $index"> 
     <md-tab-label>{{tab.tabName}}</md-tab-label> 
      <md-tab-body> 
       <div id="tab.tabName" ng-bind-html="tab.tabHTML"></div> 
      </md-tab-body> 
    </md-tab> 
</md-tabs> 

也是控制器定義爲

angular.module("MyApp").controller("myCtrl",['$log','$scope','$sce', '$compile', function myCtrl ($log,$scope,$sce,$compile) { 
    var homeScope = this; 
    homeScope.pageTabs = []; 

    var newTab = {}; 
    newTab.tabName = "Sample"; 
    newTab.tabHTML = $sce.trustAsHtml("<sample-grid></sample-grid>"); 
    newTab.tabAction = "grid"; 
    homeScope.pageTabs.push(newTab); 

    var template = angular.element(document.querySelector('#Sample')); 
    $compile(template)(homeScope); 
這一觀點

}])

要求是:使用r可以在視圖中添加新的選項卡,並且我必須根據選擇顯示視圖中的三個自定義指令之一。因此,我必須將新標籤對象與必需的屬性一起推入homeScope.pageTabs

問題是:在推送標籤對象後,新標籤被創建,但自定義指令不會渲染到視圖中。我可以看到它在控制檯中,如:

<div id="tab.tabName" ng-bind-html="tab.tabHTML"> 
    <sample-grid></sample-grid> 
</div> 

我在這裏等,我不得不使用$compile正確地呈現它看到答案。我嘗試過,但我無法得到適當的解決方案。

所以我的問題是我如何實現這個功能?而且,還有其他簡單可行的方法來實現這一目標嗎?

+0

找到我這裏的解決方案:https://stackoverflow.com/questions/38224198/angular-directive-doesnt-render-the-template-after-adding-html-dynamically-in-c – Sudip672

回答

0

我改變了你的控制器邏輯一點點。你必須使用compile有點不同。

angular.module("MyApp").controller("myCtrl",['$log','$scope','$sce', '$compile', function myCtrl ($log,$scope,$sce,$compile) { 
    var homeScope = this; 
    homeScope.pageTabs = []; 

    var template = $sce.trustAsHtml("<sample-grid></sample-grid>"); 
    var linkFn = $compile(template); 
    var content = linkFn(scope); 

    var newTab = {}; 
    newTab.tabName = "Sample"; 
    newTab.tabHTML = content; 
    newTab.tabAction = "grid"; 
    homeScope.pageTabs.push(newTab); 
}]) 
+0

'變種內容= linkFn(範圍);'這裏的範圍是指homeScope?或$範圍? – Sudip672

+0

它應該是$ scope –

+0

感謝哥們。這有很大幫助。 @benjamin。此外,我上面分享的鏈接工作,但需要一個額外的指令,但不需要$ sce和$ compile。 – Sudip672