Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Angular update object in array

Tags:

angularjs

I wanna update an object within an objects array. Is there another possibility than iterating over all items and update the one which is matching? Current code looks like the following:

angular.module('app').controller('MyController', function($scope) {
    $scope.object = {
        name: 'test',
        objects: [
            {id: 1, name: 'test1'},
            {id: 2, name: 'test2'}
        ]
    };

    $scope.update = function(id, data) {
        var objects = $scope.object.objects;

        for (var i = 0; i < objects.length; i++) {
            if (objects[i].id === id) {
                objects[i] = data;
                break;
            }
        }
    }
});
like image 717
Dominik Barann Avatar asked Nov 04 '14 17:11

Dominik Barann


1 Answers

Pass the item to your update method. Take a look at sample bellow.

function MyCtrl($scope) {
  $scope.items = 
    [
      {name: 'obj1', info: {text: 'some extra info for obj1', show: true}},
      {name: 'obj2', info: {text: 'some extra info for obj2', show: false}},
    ];
  $scope.updateName = function(item, newName){
     item.name = newName;
  } 
}
<link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.5/css/bootstrap.min.css" rel="stylesheet"/>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>

<body ng-app>
  <table ng-controller="MyCtrl" class="table table-hover table-striped">
    <tr ng-repeat="x in items">
        <td> {{ x.name }}</td>
        <td> 
           <a href="#" ng-show="!showUpdate" ng-click="someNewName = x.name; showUpdate = true">Update</a>
           <div ng-show="showUpdate" ><input type="text" ng-model="someNewName"> <input type="button" value="update" ng-click="updateName(x, someNewName); showUpdate = false;"></div>
         </td>
    </tr>

  </table>
</body>
like image 66
Artiom Avatar answered Nov 01 '22 11:11

Artiom