gpt4 book ai didi

javascript - Angular 指令使用问题

转载 作者:行者123 更新时间:2023-11-29 18:04:55 24 4
gpt4 key购买 nike

您好,我有一个要求,比如我将获取一个元素数组作为指令的属性,并且根据数组对象的大小,我必须迭代并创建模板。请在下面找到我的 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 中还提供了一个工作示例.

问题是第一个学生对象被第二个学生对象覆盖了。请告诉我如何更正它。

最佳答案

您的 element.html 更新元素的 html。您多次更新内容,最后一次更新是您最终看到的内容。使用 element.append,在迭代期间附加您的模板。

关于javascript - Angular 指令使用问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32044485/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com