oderfla
oderfla

Reputation: 1797

Radio button get unselected when removing elements

Angularjs app here. A repeat will print a table with elements. One of the column contains 4 radio buttons, while another will contain a button to delete the element.

<div ng-repeat doc in myCtrl.documents>
<input type="radio" ng-checked="doc.status == 0" ng-model="doc.status" name="status_{{doc.id}}" value="0" />Opt0
<input type="radio" ng-checked="doc.status == 1" ng-model="doc.status" name="status_{{doc.id}}" value="1" />Opt1
<input type="radio" ng-checked="doc.status == 2" ng-model="doc.status" name="status_{{doc.id}}" value="2" />Opt2
<input type="radio" ng-checked="doc.status == 3" ng-model="doc.status" name="status_{{doc.id}}" value="3" />Opt3
doc.status:{{doc.status}}
<button ng-click="myCtrl.removefunc(doc)">remove</button>

</div>  

This is the code in controller:

function removefunc(doc){
    var index = myCtrl.documents.indexOf(doc);
    documents.splice(index, 1);
}

Now, when I remove an element, if there are other listed below the one removed, a very strange thing will happen. Each two rows, the checked radio button disappears. I mean, the radio buttons are there but no one selected anymore. None of the 4 radio button is selected.

Interesting part is that the value of doc.status always show the value (0,1,2 or 3) even for those rows that lost the checked radio button.

I first tried with ng-value instead of ng-checked and also. comparing with string instead of number in the ng-checked. But still no luck. The content of the document array seems fine to me. What could be the error?

Upvotes: 0

Views: 182

Answers (2)

oderfla
oderfla

Reputation: 1797

It may sound crazy, but removing the name-attribute solved the problem. I don't know exactly why, but after that change the issue disappeared.

Upvotes: 0

Zera
Zera

Reputation: 51

I would recommend using filter(). I am not sure what would happen if you were to use indexOf() by an object.

Assuming doc.id is a unique attribute to each document object. Consider filtering the document array by the object attribute using filter(). This will just help make your code more predictable.

I would also remove ng-checked if you already have an ng-model.

Therefore changing your code to:

<div ng-repeat doc in myCtrl.documents>
<input type="radio" ng-model="doc.status" name="status_{{doc.id}}" value="0" />Opt0
<input type="radio" ng-model="doc.status" name="status_{{doc.id}}" value="1" />Opt1
<input type="radio" ng-model="doc.status" name="status_{{doc.id}}" value="2" />Opt2
<input type="radio" ng-model="doc.status" name="status_{{doc.id}}" value="3" />Opt3
doc.status:{{doc.status}}
<button ng-click="myCtrl.removefunc(doc)">remove</button>

</div>  

    function removefunc(doc) {
        myCtrl.documents = myCtrl.documents.filter(el => el.id !== doc.id);
    }

Upvotes: 1

Related Questions