我有 app.js
var app = angular.module('plunker', []);
app.controller('MainCtrl', function($scope) {
// Fetch the data from the API calls
var empDept = GetEmployeeData();
var marFin = GetFinanceData();
var x = 1;
$scope.list = {};
switch(x)
{
case 1: $scope.list = {
EmployeeDepartment: empDept
}; break;
case 2:
$scope.list = {
MarketingFinance: marFin
};break;
}
});
app.directive('myCustomer', function() {
return {
restrict: 'AE',
scope: {
customer: '=myCustomer'
},
replace: true,
templateUrl: 'EmpDept.html'
}
};
});
我的 index.html 在
下面<!DOCTYPE html>
<html ng-app="plunker">
<head>
<meta charset="utf-8" />
<title>AngularJS Plunker</title>
<script>document.write('<base href="' + document.location + '" />');</script>
<script data-semver="1.3.15" src="https://code.angularjs.org/1.3.15/angular.js" data-require="angular.js@1.3.x"></script>
<script src="app.js"></script>
</head>
<body ng-controller="MainCtrl">
<label ng-repeat="(key,val) in list">
<div ng-if="key === 'EmployeeDepartment'">
<table border="1">
<tr>
<td><b>EmployeeNames</b></td>
</tr>
<tbody>
<tr ng-repeat="customer in val" my-customer="customer"></tr>
</tbody>
</table>
<script type="text/ng-template" id="EmpDept.html">
<tr>
<td>{{customer.EmpName}}</td>
</tr>
</script>
</div>
<div ng-if="key === 'MarketingFinance'">
<table border="1">
<tr>
<td><b>Product Name</b></td>
<td><b>Price</b></td>
</tr>
<tbody>
<tr ng-repeat="customer in val" my-customer="customer"></tr>
</tbody>
</table>
<script type="text/ng-template" id="MarkFin.html">
<tr>
<td>{{customer.ProductName}}</td>
<td>{{customer.Price}}</td>
</tr>
</script>
</div>
</label>
</html>
现在的问题是
根据开关案例的值,必须更改templateURL。
例如
如果x = 1,则templateURL = EmpDept.html
如果x = 2,则templateURL = MarkFin.html
你能告诉我该怎么做吗?
N.B.~我看过this但无法插入应用程序。还有其他简单方法吗?
答案 0 :(得分:0)
我添加了一个允许您动态更改模板URL的plunker
http://plnkr.co/edit/yG5qEbFORyyNnCdVDOOY?p=preview
您必须将存储html链接的变量添加到指令范围,如下所示:
app.directive('myCustomer', function() {
return {
restrict: 'AE',
scope: {
customer: '=myCustomer',
templateHtml: "="
},
replace: true,
template: '<div ng-include="templateHtml"></div>',
link: function(scope, element, attrs) {
}
};
});