0

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.

0

1 Answer 1

2

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;
        }
    }
};
Sign up to request clarification or add additional context in comments.

2 Comments

That seemed to make it work when deleting starting at the last object in the array but not if I delete the first object or any other object first. Any ideas ?
@adamPower: From a straightforward "removing things from an array" perspective, the above should work. I can't comment on the angular parts of it; I haven't worked with angular.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.