Santhosh Aineri
Santhosh Aineri

Reputation: 559

How use checkbox properly inside ng-repeat in angularjs?

I am using ionic framework and angularjs for one app. I am using checkboxes inside ng-repeat. The issue is, if I check the checkbox, it is getting added to the array. If I uncheck it is not getting removed from that array.

The html code is

<div class="action-checkbox" ng-repeat="task in alltasks">
  <h3>{{task.taskName}}</h3>
  <ul>
    <li ng-repeat="subtask in task.subTasks" ng-click="addList(task,subtask)">
      <input id="{{task._id}}_{{subtask._id}}" name="{{task._id}}_{{subtask._id}}" type="checkbox" value="{{subtask.subTaskName}}" ng-checked="subtask.checked" ng-model="slectedTasks" class="hide"/>
      <label for="{{task._id}}_{{subtask._id}}" > 
        {{subtask.subTaskName}}
      </label>
    </li>
  </ul>
</div>

My controller code is

$scope.addList = function(task,subtask){
       subtask.checked= !(subtask.checked);
       var data = {
       "task_id": task._id,
       "subTaskName": subtask.subTaskName,
    };     
        if(subtask.checked){
         selectedMap.push(data);
        }
    }

can anyone help me to resolve this..

Upvotes: 2

Views: 149

Answers (2)

Santhosh Aineri
Santhosh Aineri

Reputation: 559

Finally I got the answer for this. If I use "selectedMap[i] === data" I am not able to splice the array because it is not able compare the objects properly. The code is

if(subtask.checked){
      //selectedMap[task._id,subtask.subTaskName] = data;
     selectedMap.push(data);
     duparray = selectedMap;
     console.log(selectedMap);
    }
    if(!subtask.checked){
      console.log("not checked");
      var sellength = selectedMap.length;
      duparray = selectedMap;
      //console.log(duparray);
             for(var i = sellength - 1; i >= 0; i--) {
                  if(selectedMap[i].subTaskName == data.subTaskName) {
                      console.log(duparray);
                        duparray.splice(i, 1);
                        console.log(duparray);
                      }
                  }
            }

Upvotes: 0

Ashish Kumawat
Ashish Kumawat

Reputation: 695

Add code to remove element also.

if(subtask.checked == false){
             for(var i = selectedMap.length - 1; i >= 0; i--) {
                  if(selectedMap[i] === data) {
                        selectedMap.splice(i, 1);
                      }
                  }
            }

Upvotes: 1

Related Questions