2016-09-20 45 views
1

我試圖加載指令是有條件的模板,爲示例 -有條件裝載模板的角度指令

.directive('truncate',["$window", function($window, $compile){ 
    return { 
     restrict: 'A', 
     templateUrl: 'template/truncate.html', 
     link: function (scope, element, attrs) { 
     var height = element[0].offsetHeight; 
     var shouldBetruncated = height>200; 
     if(shouldBetruncated){ 
      // want my template to load here, otherwise template is not loaded 
     }; 
     } 
    } 
}]) 
.run(function ($templateCache) { 
     $templateCache.put('template/truncate.html', 
      'template code' 
     ); 
}) 

反正是有達致這?

+0

你爲什麼需要這個? –

回答

0
/*This will solve you problem*/ 


link: ... 
templateUrl: function() { 
    if(shouldBetruncated) { 
     return 'template/truncate.html'; 
    } else { 
     return ''; 
    } 
} 

欲瞭解更多信息,你可以通過HTML模板或基於條件

+0

templateUrl:'template/truncate.html',這是一個對象語法,你確定它可以在這裏用作不工作 – madhur

+0

如果條件應該在鏈接函數之外 –

+0

但是問題在於我的條件將被評估鏈接功能只,所以需要從這裏申請這 – madhur

0

嘗試......

.directive('truncate',["$window", function($window, $compile){ 
    return { 
    restrict: 'A', 
    templateUrl: 'template/truncate.html', 
    link: function (scope, element, attrs) { 
    var height = element[0].offsetHeight; 
    shouldBetruncated = height>200; 
    if(shouldBetruncated){ 
     loadTemplate(); 
    }; 
// function loadTemplate -- begins 
var loadTemplate = function ($templateCache) { 
      $templateCache.put('template/truncate.html', 
     'template code' 
    ); 
     }; 
// -- ends 

    } 

}} ]);

+0

指令無法找到模板,直到loadTemplate函數運行,因此它會引發錯誤 – madhur

+0

您可以創建一個plunkr鏈接,以便它可以幫助解決該問題。 –