一尘不染

如何使templateURL根据传递的数据在运行时加载HTML模板?

angularjs

我正在遵循Template-
expanding指令
的示例

在此处输入图片说明

一切正常。现在,我尝试将概念扩展如下。

app.js

var app = angular.module('app', []);
app.controller('Ctrl', function ($scope) {

    var EmpData = [{
      "EmpId": 1,
      "EmpName": "Michale Sharma"
    }, {
      "EmpId": 2,
      "EmpName": "Sunil Das"
    }
  ];
  var DeptData= [{
    "Deptid": 4,
    "Deptname": "IT"
  }, {
    "Deptid": 1,
    "Deptname": "HR"
  }];

    $scope.customer = {
      EmployeeRelatedData: EmpData,
      DepartmentRelatedData: DeptData
    }; 
});

app.directive('myCustomer', function() {
  return {
    templateUrl: function(elem, attr){
      return attr.type+'.html';
    }
  };
});

index.html

<!DOCTYPE html>
<html>

  <head>
    <meta charset="utf-8" />       
    <script>document.write('<base href="' + document.location + '" />');</script>
    <link href="style.css" rel="stylesheet" />
    <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-app="app" ng-controller="Ctrl">

    <div ng-controller="Ctrl">

    <!-- Section for Employee -->
      <div my-customer type="EmployeeRelatedData">

        <table border="1">
          <thead>
              <tr>
                  <th>Employee Id</th>
                  <th>Employee Name</th>                 
              </tr>
          </thead>
          <tbody>
            <tr ng-repeat="x in customer.EmployeeRelatedData"></tr>
          </tbody>
        </table>

        </div>

      <!-- Section for Department -->
      <div my-customer type="DepartmentRelatedData">

        <table border="1">
          <thead>
              <tr>
                  <th>Department Id</th>
                  <th>Department Name</th>                 
              </tr>
          </thead>
          <tbody>
            <tr ng-repeat="x in customer.DepartmentRelatedData"></tr>
          </tbody>
        </table>

      </div>

    </div>

</body>

</html>

EmployeeRelatedData.html

<tr>
      <td>{{customer.EmpId}}</td>
      <td>{{customer.EmpName}}</td>     
</tr>

DepartmentRelatedData.html

<tr>
      <td>{{customer.Deptid}}</td>
      <td>{{customer.Deptname}}</td>     
</tr>

我正在寻找输出

在此处输入图片说明

我无法解决的错误是什么?谢谢。


阅读 133

收藏
2020-07-04

共1个答案

一尘不染

您犯了一些错误,请在此处查看工作演示

http://plnkr.co/edit/RQ1xWaLUAsBpNgyMWujI?p=preview

my-customer should be inside tr tag not before table

您需要将客户传递到指令范围,以便通过创建隔离范围来实现

 scope: {

      customer: '=myCustomer'
    },

在你看来

my-customer="x"

因为x是您的客户

2020-07-04