2015-10-16 67 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

好的,明白了你的观点。还有一个问题:我不明白以下变量元素是什么?它从何而来? –