javascript - 使用 JQuery 时数组不更新

标签 javascript jquery arrays angularjs

我正在尝试拼接数组以便从数组中删除一个对象。我使用 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() 但无济于事。

最佳答案

您的函数中有几个逻辑错误:

  1. 当您从数组中删除一个项目时,无论如何都会增加 i,这意味着您将错过下一个匹配的项目。

  2. 您在 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/

相关文章:

javascript - 将选定的选项附加到选择器

javascript - jQuery根据像素调整百分比宽度调整margin-Left

jquery - 使用 JQuery 修改 animate 函数

javascript - 将 div 附加到所选文本

javascript - Backbone 过滤器集合按名称返回模型?

javascript - 调用输入的点击事件在 Safari 中不起作用

jQuery Mobile 动态添加元素

arrays - FireStore 和 map /数组,Kotlin 中的文档列表到数组

c - 将文件中的字符串存储到数组中

arrays - swift 发现 fatal error 为零