我想基于$ 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>
问题是:如何根据templateUrl
值设置customerType.getCustomerType()
变量?目前,template
的值未定义。
答案 0 :(得分:0)
您可以使用$http
服务根据指令链接函数中的客户类型动态获取html字符串,然后使用$compile
将html字符串与您的范围绑定,最后替换<create-menu-tree>
内容使用新的编译元素
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){}
}
}
}]);