我正在尝试拼接数组以便从数组中删除一个对象。我使用 Angular-formly 来显示表单,并使用 AngularJs 和 JQuery 来处理数据。
JQuery
$(document).on("click", ".delete-me", function () {
var id = $(this).parent().find('input, select, textarea').attr('id');
var splitid = id.split("_")[3];
angular.element(document.getElementById('View2Ctrl')).scope().removeField(splitid);
$(this).closest('.formly-field').remove();
});
拆分的原因是,它正式包装了一个 id,如 formly_1_input_textField-1_0。
Angular 函数
$scope.removeField = function (id) {
for(var i=0;i<$scope.formFields.length;i++){
if($scope.formFields[i].key == id){
$scope.formFields.splice(id, 1);
console.log($scope.formFields.length);
$scope.currentId = i;
}
}
};
控制台日志显示数组的实际长度,但是我在模板上有 {{formFields.length}} 并且它不会更新,并且 {{formFields}} 仍然显示数组中的数据。我怀疑 Angular 没有监视 JQuery 更新 DOM,并尝试手动调用 $scope.$apply() 但无济于事。
最佳答案
您的函数中有几个逻辑错误:
当您从数组中删除一个项目时,无论如何都会增加
i
,这意味着您将错过下一个匹配的项目。您在
splice
中使用id
而不是i
第二个可能是罪魁祸首,但是一旦你解决了这个问题,第一个就会咬你(除非 id
值是唯一的,顾名思义;在这种情况下,你当你找到它时可能应该终止循环)。
更新:
$scope.removeField = function (id) {
var i=0;
while (i<$scope.formFields.length){ // Use a while loop
if($scope.formFields[i].key == id){
$scope.formFields.splice(i, 1); // Use i, not id
console.log($scope.formFields.length);
$scope.currentId = i;
// DON'T increment i here, you've removed the element
// Or if IDs are unique, just terminate the loop
} else {
++i;
}
}
};
关于javascript - 使用 JQuery 时数组不更新,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28631068/