t3__rry
t3__rry

Reputation: 2849

AngularJs: uncheck checkbox after item is removed

after spending a lot of time on this simple issue and having made a lot of research, I was wondering if someone could give me some help.

I have data which is generated inside of a table like so:

<tbody>
     <tr class="odd gradeX" ng-repeat="user in ctrl.datas | orderBy:ctrl.sortType:ctrl.sortTypeReverse">
     <td>
        <input type="checkbox" class="checkboxes" value="{{user.id}}" ng-click="ctrl.addItem(user)"/>
     </td>
     <td>
       {{user.given_name}}
     </td>

     <td>
         {{user.family_name}}
     </td>
     <td>
       <a href="mailto:{{user.emai}}"> {{user.email}}</a>
     </td>
     <td class="center" ng-bind-html="ctrl.convertToDate(user.created_at) | date: 'dd-MMMM-yyyy hh:mm'"></td>
     <td>
       <span class="btn blue-hoki"> Details </span>
     </td>
    </tr>
</tbody>

Above is a container where I get the items selected via a checkbox, add the in an array and give the user the ability to delete the selected item:

<tr ng-repeat="user in ctrl.checkedObject track by $index" ng-show="user.id">
   <td>{{user.family_name}}</td>
   <td>{{user.given_name}}</td>
   <td>
      <button class="btn blue" ng-click="ctrl.removeItem($index)">Unselect</button>
    </td>
</tr>

In my controller, here are the two functions used to do so:

this.checkedObject = [];

//Add selected user

this.addItem = function (user) {
   self.checkedObject.push(user);
};
this.removeItem = function(obj){
   delete self.checkedObject[obj];
};

What i'd like to achieve is to uncheck the corresponding checkbox if a user changes his selection. The thing is, I have no idea how to target the corresponding checkbox. Does anyone have a clue? Thanks in advance

Upvotes: 0

Views: 2136

Answers (2)

Bennett Adams
Bennett Adams

Reputation: 1818

I set up a simple plunker to show one approach, which would be to assign a selected property to each user when his/her checkbox is checked, and set an ng-checked attribute on the checkbox corresponding to user.selected (so will be unchecked when false).

Using this approach you won't need to push and delete from the array of checkedUsers, you can just filter all the users by whether they are selected or not.

function getSelected() {
  ctrl.checkedObject = _.filter(ctrl.datas, {selected: true});
}

ctrl.selectUser = function (user) {
   user.selected = true;
   getSelected();
};
ctrl.removeUser = function(user){
   user.selected = false;
   getSelected();
};

Upvotes: 1

Eigi
Eigi

Reputation: 716

Try ng-checked like:

 <input type="checkbox" ng-checked="user !== null" class="checkboxes" value="{{user.id}}" ng-click="ctrl.addItem(user)"/>

And set the item (user) to null on button click (inside removeItem() ) or a other variable.

Upvotes: 2

Related Questions