嗨我有一个要求,就像我会得到一个元素数组作为指令的属性,并根据数组对象的大小,我必须迭代并创建模板。请在下面找到我的JS类。
mainApp.directive('student', function() {
var directive = {};
directive.restrict = 'E';
directive.template = "Student: <b>{{student.name}}</b> , Roll No: <b>{{student.rollno}}</b>";
directive.scope = {
student : "=name"
}
directive.compile = function(element, attributes) {
element.css("border", "1px solid #cccccc");
var linkFunction = function($scope, element, attributes) {
for (i = 0;i<$scope.student.length;i++){
element.html("Student: <b>"+$scope.student[i].name +"</b> , Roll No: <b>"+$scope.student[i].rollno+"</b><br/>");
}
}
return linkFunction;
}
return directive;
});
我的数据就像
$scope.students = [
{
name:"TestName1",
rollno:2
},
{
name:"TestName2",
rollno:1
}
];
我的HTML就像
<student name="students"></student><br/>
plunker还提供了一个工作示例。
问题是第一个学生对象被第二个学生对象覆盖。请让我知道如何纠正它。
答案 0 :(得分:3)
您的element.html
更新元素的html。您正在多次更新内容,最后一次更新是您最终看到的内容。使用element.append
,在迭代过程中附加模板。
答案 1 :(得分:1)
你走了:
mainApp.directive('student', function() {
var directive = {};
directive.restrict = 'E';
directive.template = "Student: <b>{{student.name}}</b> , Roll No: <b>{{student.rollno}}</b>";
directive.scope = {
student : "=name"
};
directive.compile = function(element, attributes) {
element.css("border", "1px solid #cccccc");
var linkFunction = function($scope, element, attributes) {
for (i = 0;i<$scope.student.length;i++){
element.append("Student: <b>"+$scope.student[i].name +"</b> , Roll No: <b>"+$scope.student[i].rollno+"</b><br/>");
}
}
return linkFunction;
}
return directive;
});
您必须使用element.append()
代替element.html()