AngularJs指令在返回模板数据之前呈现
问题描述:
您好,我试图从AngularJs指令中返回表并将其绑定。AngularJs指令在返回模板数据之前呈现
我的角码是:
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指令返回HTML绑定后的表
答
既然你正在为请求后端(我认为)在
employeeDataServices.getEmployees()
您不能在指令中使用模板属性。为了实现您的功能,您可以使用帖子链接功能
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;
}
没有时间去验证,但你得到了要点。
+0
感谢您的回复,它适合我。 –
+0
你能接受答案吗? –
+0
确定我现在正在做。 –
是的,不,真的,这不是应该如何使用angularjs。你不明白异步。模板是纯粹静态的HTML。通过使用角度表达式,在模板内使用ng-repeat等,并绑定到数据,可以使其动态化。暂时忘记指令,只是了解基本的控制器和视图。 –