简体   繁体   中英

Array not updating when using JQuery

I'm trying to splice an array in order to delete an object from my array. I'm using angular-formly to display the forms and AngularJs and JQuery in order to handle the data.

The 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();
});

The reason for the split and is that formly wraps an id like formly_1_input_textField-1_0 .

The Angular Function

 $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;
            }
        }
    };

The console log is displaying the actual length of the array however I have {{formFields.length}} on the template and it does not update, as well as {{formFields}} still showing the data in the array. I suspect that JQuery updating the DOM isn't being watched by Angular and have tried calling $scope.$apply() manually to no avail.

You have a couple of logic errors in your function:

  1. When you remove an item from the array, you increase i anyway, which means you'll miss out the next item if it's a match.

  2. You're using id instead of i in the splice

That second one is probably the culprit, but once you'd fixed that, the first would have bitten you (unless the id values are unique, as the name implies; in which case, you should probably terminate the loop when you find it).

Updates:

$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;
        }
    }
};

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM