Santhosh Aineri
Santhosh Aineri

Reputation: 559

How to push objects into arrays in angularjs?

I am using Ionic Framework and angularjs to develop one application. Here I am using checkbox inside ng-repeat. Using this I can able to insert checkbox checked values into array. But It is inserting like strings.

Like ["coding","testing"] .

But I want it like objects.

Like ["object","object"] . Inside that object values should be there.

Html code is

<div class="action-checkbox" ng-repeat="task in projecttasks">
      <h3>{{task.projectName}}</h3>
      <ul>
        <li ng-repeat="subtask in task.subTasks" ng-click="addprjtaskList(task,subtask)">
          <input id="{{subtask._id}}" name="{{subtask._id}}" type="checkbox" value="{{subtask.subTaskName}}" ng-checked="selection.indexOf(subtask.subTaskName) > -1" ng-click="toggleSelection(subtask.subTaskName)" class="hide"/>
          <label for="{{subtask._id}}" > 
            {{subtask.subTaskName}}
          </label>
        </li>
      </ul>
    </div>

controller code is

$scope.selection = [];
  // toggle selection for a given fruit by name
    $scope.toggleSelection = function toggleSelection(fruitName) {
      var idx = $scope.selection.indexOf(fruitName);
      // is currently selected
      if (idx > -1) {
        $scope.selection.splice(idx, 1);
        console.log($scope.selection);
      }

      // is newly selected
      else {
        $scope.selection.push(fruitName);
        console.log($scope.selection);
      }
    };

can anyone help me to do this..

Upvotes: 0

Views: 1050

Answers (2)

danday74
danday74

Reputation: 57231

in toggleSelection(fruitName) you are passing a string

then you are doing

$scope.selection.push(fruitName)

it is doing what it is told!

you need to pass the object to the function ...

ng-click="toggleSelection(subtask.subTaskName)"

SHOULD BE ...

ng-click="toggleSelection(subtask)"

AND THEN ...

push that instead!

Upvotes: 4

Jon
Jon

Reputation: 1095

What I think you're looking for is to push subtask into an array, not subtask.subTaskName.

You'll have to change your view to ng-click="toggleSelection(subtask)" to reference the object instead of the object's name.

You'll also have to modify your ng-checked="selection.indexOf(subtask.subTaskName) > -1 to reference a new function that checks for duplicity (since indexOf() doesn't like object arrays) . I'll go into that further next.

Next, you'll have to update your controller to test for duplicates. I suggest making a separate method using a for loop to iterate through your array, checking subTaskName for equality instead of indexOf(). By making a separate method, you remove logic from your html, and allow code reuse. A double win!

Then, you'll just have to push the object normally, and you're done!

Upvotes: 2

Related Questions