这是div有ng-repeat。我试图为每个文件附加一个图像。
<div class = "fileslink" ng-repeat="file in files" id = "filegen" my-repeat-directive>
.... ` 这会创建图像,并在页面加载时调用:
function filesInFolder(i){
$scope.files = [];
$http.get("/restricted/getFileList?folder=" + i + "&withComments=True")
.then(function (response) {
if (response.data.status != 'Failed' && response.data != []){
for (var j=0; j<response.data.length; j++){
var newFile = {};
newFile.fileName = response.data[j].fileName;
newFile.folder = i;
//alert("folder: " + newFile.folder);
newFile.comment = response.data[j].comment;
newFile.selected = false;
newFile.editingComment = false;
newFile.date = getDate(newFile.fileName, newFile.folder);
$scope.files.push(newFile);
var imageElem = document.createElement("img");
imageElem.src = "/Additional%20Files/icons/" + fileType(response.data[j].fileName) + ".png";
console.log(response.data[j].fileName);
imageElem.height = "37";
imageElem.width = "31";
imageElem.style.position = "absolute";
imageElem.style.top = "7px";
imageElem.style.left = "18px";
imageElem.style.paddingBottom = "2px";
imageElem.style.border = "2px solid black";
console.log("name inside folder: " + response.data[j].fileName + ", src: " +imageElem.src);
}
}
});
};
指令
app.directive('myRepeatDirective', function() {
var boxes = document.getElementsByClassName("fileslink");
//console.log(boxes.length);
return function(scope, element, attrs) {
for (var x = 0; x < boxes.length; x++) {
console.log("x: " + x + ", val: ");
boxes[x].appendChild(imageElement);
};
angular.element(element).css('border', '2px solid red');
if (scope.$last) {
window.alert("im the last!");
}
};
});
现在,图像仅显示在第一个文件(索引0)上,而不显示在其他文件上。我在这里缺少什么?
仍然是新的角度btw,所以如果你有更有效的方法来编写代码,这将有所帮助。
答案 0 :(得分:1)
你应该等到ng-repeat
呈现它的所有元素。然后你应该附加一个图像元素。您已经有条件检查ng-repeat
完成其呈现,if(scope.$last)
是一个条件,表示已呈现ng-repeat
的所有元素。
<强>指令强>
app.directive('myRepeatDirective', function() {
return function(scope, element, attrs) {
angular.element(element).css('border', '2px solid red');
if (scope.$last) {
var boxes = document.getElementsByClassName("fileslink");
window.alert("im the last!");
console.log(boxes.length); //all element must be rendered
for (var x = 0; x < boxes.length; x++) {
console.log("x: " + x + ", val: ");
boxes[x].appendChild(imageElement);
};
}
};
});