此代码使用指令显示集合中的客户:
http://jsfiddle.net/edwardtanguay/kj4oj1aa/2
集合:
$scope.customers = [
{'kind':'internal', 'firstName':'Jim', 'lastName':'Thompson', 'age':'34', 'internalcode':'X3434'},
{'kind':'external', 'firstName':'James', 'lastName':'Hankerton', 'age':'33','website':'http://google.com'},
{'kind':'undefined', 'firstName':'Greg', 'lastName':'Garland', 'age':'28'},
{'kind':'external', 'firstName':'Eddie', 'lastName':'Eddington', 'age':'33','website':'http://yahoo.com'},
{'kind':'internal', 'firstName':'Rachael', 'lastName':'Rosters', 'age':'34', 'internalcode':'X1112'},
{'kind':'undefined', 'firstName':'David', 'lastName':'Dielan', 'age':'37'},
{'kind':'undefined', 'firstName':'Howard', 'lastName':'Honduras', 'age':'45'}
];
在我的指令中,我目前一直在调用itemMenuTemplateUndefined
模板:
return {
restrict: 'A',
scope: {
datasource: '=',
add: '&'
},
controller: controller,
controllerAs: 'vm',
bindToController: true,
templateUrl: 'itemMenuTemplateUndefined'
};
调用此模板:
<script type="text/ng-template" id="itemMenuTemplateUndefined">
<div ng-repeat="item in vm.items track by $index">
<div class="panel panel-default">
<div class="panel-heading">
{{item.firstName}} {{item.lastName}}
</div>
<div class="panel-body">
Age: {{item.age}}
</div>
</div>
</div>
</script>
但是,根据我的指示,我想根据 customer.kind = internal
,external
或undefined
来调用不同的模板,
e.g。 内部客户的模板:
<script type="text/ng-template" id="itemMenuTemplateInternal">
<div ng-repeat="item in vm.items track by $index">
<div class="panel panel-success">
<div class="panel-heading">
{{item.firstName}} {{item.lastName}}
</div>
<div class="panel-body">
<div>Age: {{item.age}}</div>
<div>Internal Code: {{item.internalcode}}</div>
</div>
</div>
</div>
</script>
以及外部客户的模板:
<script type="text/ng-template" id="itemMenuTemplateExternal">
<div ng-repeat="item in vm.items track by $index">
<div class="panel panel-warning">
<div class="panel-heading">
{{item.firstName}} {{item.lastName}}
</div>
<div class="panel-body">
<div>Age: {{item.age}}</div>
<div>Website: {{item.website}}</div>
</div>
</div>
</div>
</script>
我在哪里放置逻辑,以便指令可以根据customer.kind
决定显示哪个模板?
答案 0 :(得分:1)
您可以使用ng-include
这样的内容:
return {
restrict: 'A',
scope: {
datasource: '=',
add: '&'
},
controller: controller,
controllerAs: 'vm',
bindToController: true,
template: '<div ng-include="getTemplateUrl()"></div>',
link: function(scope, element, attrs) {
scope.getTemplateUrl = function() {
// add here your logic and return the relative path
};
},
};
以下是我将针对您的案例采用的解决方案:JSFiddle