2015-10-16 65 views
0

我想根據$ watch動態生成指令。這裏是我的代碼,只需登錄服務對象的值:

gasStation.directive('createMenuTree', ['customerType', function (customerType) { 
    console.log(customerType.getCustomerType() + ' enterring a directive'); 
    var template; 


    console.log(customerType.getCustomerType() + ' from directive'); 

    var linker = function(scope){console.log()} 

    return { 

     controller: ['$scope', function ($scope) {}], 

     link: function(scope){ 
      scope.$watch(function(){ 
       console.log(customerType.getCustomerType() + ' watcher'); 
       if (customerType.getCustomerType() == 'REGULAR') { 
        template = 'dashboard/regular_dashboard.html'; 
       } 
       if (customerType.getCustomerType() == 'BUSINESS') { 
        template = 'dashboard/business_dashboard.html'; 
       } 
       return customerType.getCustomerType(); 
      }); 
     }, 

     templateUrl: template 
    }; 
}]); 

我如何使用指令:<create-menu-tree></create-menu-tree>

的問題是:如何我可以設置基於該customerType.getCustomerType()價值templateUrl變量?目前,template的值未定義。

回答

0

您可以使用$http服務動態獲取HTML字符串根據客戶類型向鏈路功能,然後使用$compile到HTML字符串與範圍結合,最後用新的編譯元素

gasStation.directive('createMenuTree', ['customerType', '$compile', '$http', 

function (customerType, $compile, $http) { 
    return { 
     restrict:'EA', 
     template: '', 
     scope:false, 
     compile: function(){ 
      return { 
       pre: function(scope, element, attr){ 

        var templateUrl = ''; 

        if (customerType.getCustomerType() == 'REGULAR') { 
         templateUrl = 'dashboard/regular_dashboard.html'; 
        } 
        if (customerType.getCustomerType() == 'BUSINESS') { 
         templateUrl = 'dashboard/business_dashboard.html'; 
        } 

        $http.get(templateUrl).then(function(htmlString){ 
         var templateEle = $compile(htmlString)(scope); 
         element.empty(); 
         element.append(tempalteEle); 
        }) 

       }, 
       post: function(scope, element, attr){} 
     } 
    } 
}]); 
+0

謝謝更換<create-menu-tree>內容你的回覆。是否有可能避免使用$ http服務?這可能是矯枉過正... –

+0

是的,你可以避免使用'$ http'。它基於你存儲你的模板的地方。在這裏,我想你把模板放在一個單獨的html文件中。你可以使用[$ templateCache](https://docs.angularjs.org/api/ng/service/$templateCache)來存儲和獲取模板 – MarkoCen

+0

好的,明白了你的觀點。還有一個問題:我不明白以下變量元素是什麼?它從何而來? –