Angular Array Mutate

by David Rodenas

HTML

<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.6.2/angular.js"></script>
<div ng-app="myApp" ng-controller="MyCtrl as ctrl">
  <ul>
    <li ng-repeat="item in ctrl.inventory">
      {{ item.name }} - ${{ item.price }}
    </li>
  </ul>
  First item: {{ ctrl.inventory[0].name }} - ${{ ctrl.inventory[0].price }}<br>
  Second item: {{ ctrl.inventory[1].name }} - ${{ ctrl.inventory[1].price }}<br>
  <button ng-click="ctrl.swap()">Swap</button>
  <button ng-click="ctrl.swapAndIncrease()">Swap and Increase</button>
</div>

JavaScript

var myApp = angular.module('myApp',[]);

myApp.controller('MyCtrl', function() {
	this.inventory = [
    {name: 'MacBook Air', price: 1000},
    {name: 'MacBook Pro', price: 1800},
    {name: 'Lenovo W530', price: 1400},
    {name: 'Acer Aspire One', price: 300}
  ];
  
  this.swap = function() {
    var t = this.inventory[0];
    this.inventory[0] = this.inventory[1];
    this.inventory[1] = t;
  };
  
  this.swapAndIncrease = function() {
  	this.swap();
    this.inventory[0].price += 100;
  };
});