xeon48 February 2016

checkbox unchecking itself after angularjs filter applied

This causes the same item to be added to the array - which is used for querying - potentially twice. When the modal is closed and opened again and filtering is not used, everything is fine (this is because my modals are simply within the HTML, I just ng-hide them on click). When an item which has already been added, but its checkmark has been lost due to filtering, is checked again two of the same items are added. When it is unchecked both are removed, unless it is the last item in the array, this cannot be removed (I'm aware this is my slapdash logic). Below is the relevant HTML and JavaScript code (famous last words).


<div style="display: inline-block;" ng-controller="modalCtrl">
                <button ng-click="showModal = !showModal">Entities</button>
                <div ng-init="showModal=false">
                    <div class="modal fade in" aria-hidden="false"
                        style="display: block;" ng-show="showModal">
                        <div class="modal-dialog">
                            <div class="modal-content">
                                        <input type="text" placeholder="Search" ng-model="simpleFilter">
                                        <button type="button" ng-click="showModal=false">Ok</button>
                                <div ng-repeat="entity in entityArray | filter:simpleFilter">

                                    <label> <input
                                        style="display: inline-block; margin-top: 5px"
                                        type="checkbox" ng-model="entityChecked"


SoluableNonagon February 2016

entityChecked is not declared anywhere in your javascript, so each time you filter, entityChecked is reset, so you need to make the model something that the repeater will see and have access to.

           <!-- entity is now in the created child scope -->
<div ng-repeat="entity in entityArray | filter:simpleFilter">
    <label> <input style="display: inline-block; margin-top: 5px"

         <!-- set the checked value on the 'entity' itself, then it will be  retained -->
         type="checkbox" ng-model="entity.entityChecked"

         ng-change="getEntityFromModal(entity, entityChecked)" /> <a>{{entity}}</a>

xeon48 February 2016

Finally have an answer - the array holding my values entityArray needs to be changed into an array holding JSON values, and for each value val there must be a value checked , which is represented by ng-model - in the above case it would be passed to getEntityFromModal(entity, entity.checked).

working plnk - https://plnkr.co/edit/2ptIAdOyaIw8mGqpU7Cp?p=preview

Post Status

Asked in February 2016
Viewed 3,585 times
Voted 13
Answered 2 times


Leave an answer