Ebtic Bobo Ebtic Bobo - 7 months ago 15
Javascript Question

Resetting the value of a Input box in Angular JS

I have the following simple Angular app.

HTML

<!DOCTYPE html>
<html ng-app="myApp">
<head>
<title>Shopping</title>
<script src="../js_libs/angular.min.js"></script>
<script src="controller.js"></script>
<link rel="stylesheet" href="../css/bootstrap.css"/>
</head>
<body ng-controller="MainController">
<h1><span class="label label-default">{{title}}</span></h1>
<br/>
<table class="table">
<thead>
<tr>
<th>Item</th>
<th>Unit price</th>
<th>Quantity</th>
<th>Total price</th>
</tr>
</thead>
<tbody>
<tr ng-repeat="item in items">
<td>{{item.title}}</td>
<td>{{item.price}}</td>
<td><input name="qty" type="text" ng-model="qty"/></td>
<td>{{((item.price * qty) || 0) | number}}</td>
<td><button ng-click="reset($index)">Reset</td>
</tr>
</tbody>
</table>
</body>




controller.js file:

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

myApp.controller('MainController', function($scope) {
$scope.title = 'Shopping Items';
$scope.items = [{title: 'Item1', price: 3.95},
{title: 'Item2', price: 12.95},
{title: 'Item3', price: 6.95}];
$scope.reset = function($index){

$scope.qty[index] = "";
}
});


When I click a button from a row, the value in Input box from that row (i.e. qty) should be 0, and also the column "Total price" should be modified to 0. But this is not happening ? What should I add ?

Answer

qty is not a key of the object, change model name to item.qty and while accessing it from array, refer index of the object

Note: Also consider typo at [index], you are accepting argument as $index but while accessing the key, using index

Suggestion: type='number' for <input> is more appropriate for your use-case

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

myApp.controller('MainController', function($scope) {
  $scope.title = 'Shopping Items';
  $scope.items = [{
    title: 'Item1',
    price: 3.95
  }, {
    title: 'Item2',
    price: 12.95
  }, {
    title: 'Item3',
    price: 6.95
  }];
  $scope.reset = function(index) {
    $scope.items[index].qty = "";
  }
});
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.15/angular.min.js"></script>

<body ng-app='myApp' ng-controller="MainController">
  <h1><span class="label label-default">{{title}}</span></h1>
  <br/>
  <table class="table">
    <thead>
      <tr>
        <th>Item</th>
        <th>Unit price</th>
        <th>Quantity</th>
        <th>Total price</th>
      </tr>
    </thead>
    <tbody>
      <tr ng-repeat="item in items">
        <td>{{item.title}}</td>
        <td>{{item.price}}</td>
        <td>
          <input name="qty" type="number" ng-model="item.qty" />
        </td>
        <td>{{((item.price * item.qty) || 0) | number}}</td>
        <td>
          <button ng-click="reset($index)">Reset</button>
        </td>
      </tr>
    </tbody>
  </table>
</body>

Fiddle Demo