AngularJs 指令在返回模板数据之前呈现

AngularJs directive renders before returning the template data

您好,我正在尝试从 AngularJs 指令 return table 并绑定它。

我的angular代码是:

function directive($window, employeeDataServices) {
    var directive = {
      link: link,
      restrict: 'EA',
      renderOnFirstLoad: false,
      template: myData()
    };
    return directive;
    function link(scope, element, attrs) {
    }
    function myData() {
      angular.element(document).ready(function () {
        employeeDataServices.getEmployees().then(function (response) {
          var table = "<table>";
          table += "<tr>";
          table += "<th>Id</th>";
          table += "<th>Name</th>";
          table += "</tr>";
          angular.forEach(response, function (value, key) {
            table += "<tr>";
            table += "<td>" + value.Id + "</td>";
            table += "<td>" + value.Name + "</td>";
            table += "</tr>";
          });
          table += "</table>";
          return table;
        });
      });
    }
  }

而在 html 我正在使用

<div directive></div>

AngularJs 指令 return 是 html 绑定后的 table

由于您在

中向后端发出请求(我认为)
employeeDataServices.getEmployees()

您不能在指令中使用模板 属性。为了实现您的功能,您可以使用 post link function

function directive($window, employeeDataServices) {
var directive = {
    restrict: 'EA',
    renderOnFirstLoad: false,
    compile: function () {
        return {
            post: function (scope, element, attrs) {
                employeeDataServices.getEmployees().then(function (response) {
                    var table = "<table>";
                    table += "<tr>";
                    table += "<th>Id</th>";
                    table += "<th>Name</th>";
                    table += "</tr>";
                    angular.forEach(response, function (value, key) {
                        table += "<tr>";
                        table += "<td>" + value.Id + "</td>";
                        table += "<td>" + value.Name + "</td>";
                        table += "</tr>";
                    });
                    table += "</table>";
                    element.append(table);
                });
            }
        }
    }
};
return directive;
}

没来得及验证,但你明白了要点。