简体   繁体   English

将项目从一个数组推送到Angular中的另一个数组

[英]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. 我正在使用AngularJS编写应用程序,并想知道如何将项目从一个数组推送到另一个数组。

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? 如何将值为“Do the dishes”的项目推送到tasksDone数组?

$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. 上面的代码将每个包含值的对象作为特定值推送...您可以通过传递“Do the dishes”值作为参数来调用addToTasksDone。

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) . 我有一个ng-repeat内的列表所以我必须将$scope.addToTasksDone(index)更改$scope.addToTasksDone(index) $scope.addToTasksDone($index)

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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