Znowman Znowman - 1 month ago 16
AngularJS Question

Angularjs rename items in an array

Adding items from one array to a new array using:

$scope.listItems = [];
$scope.addToList = function(item) {
$scope.listItems.push(item);
console.log($scope.listItems);
};

<tr ng-repeat="x in data">
<td><{{ x.id }}</td>
<td><button type="button" ng-click="addToList(x.id)">Add to</button></td>
</tr>


Then printing the new array:

<tr ng-repeat="item in listItems">
<td>{{item.id}}</td>
</tr>


Would it be possible to change the attribute names of the new listItems array using user input?

M B M B
Answer

Sure its possible. But not the way your code is written. You need to pass the object to the function, not the id.

<tr ng-repeat="x in data">
  <td>{{ x.id }}</td>
  <td><input type="text" ng-model="newVal"/></td> <!--this property can be changed by user-->
  <td><button type="button" ng-click="addToList(x, newVal)">Add to</button></td>
</tr>

and in the controller function:

  $scope.addToList = function(item, newVal) {
     var newItem = item;
     newItem.id =  newVal;
     $scope.listItems.push(item);
     console.log($scope.listItems);
  };