简体   繁体   中英

Push Item From One Array Into another Array in Angular


I am programming an app with AngularJS and wanted to know how to push an item from one array into another array.

Here is sample code:

$scope.tasks = [
     {title: "Do the dishes"},
     {title: "Walk the dog"},
];
$scope.addToTasksDone = function() {// IM FAILNG HERE};
$scope.tasksDone = [];

How can I push the item with value "Do the dishes" to the tasksDone array?

$scope.tasks = [
{title: "Do the dishes"},
{title: "Walk the dog"},
];
$scope.tasksDone = [];
$scope.addToTasksDone = function(index) {// IM FAILNG HERE};
$scope.tasksDone.push($scope.tasks[index]);
}
$scope.tasks.push(yourObject)

这个问题在此之前已经过

$scope.tasks = [
    { title: "Do the dishes" },
    { title: "Walk the dog" }
]; 
$scope.tasksDone = [];
for(var i in $scope.tasks){
    $scope.tasksDone.push($scope.tasks[i]);
}
$scope.tasks = [
{title: "Do the dishes"},
{title: "Walk the dog"},
];
 $scope.tasksDone = [];
angular.forEach(tasks , function(value, key) {
  this.push(key + ': ' + value);
},tasksDone);
};

you can use the following code to push some specific value to the new array

$scope.tasks = [
     {title: "Do the dishes"},
     {title: "Walk the dog"},
];
$scope.tasksDone = [];
$scope.addToTasksDone = function(specificValue) {
                           // IM FAILNG HERE};
     tasks.forEach( (object) => {
          if ( object[title] === specificValue ) {
                $scope.tasksDone.push(object);
          }
     });
}

Above code will push each object which contain value as specific Value... You can invoke addToTasksDone by passing "Do the dishes" value as parameter.

Sample invocation

$scope.addToTasksDone("Do the dishes");

Regards

Ajay

This is the right code.

I have the list inside a ng-repeat so i have to change $scope.addToTasksDone(index) to $scope.addToTasksDone($index) .

Ofcourse also in the HTML for example : ng-click="addToTasksDone($index)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM