簡體   English   中英

在 Angular JS 中重置輸入框的值

[英]Resetting the value of a Input box in Angular JS

我有以下簡單的 Angular 應用程序。

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>

控制器.js文件:

  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] = "";
}
});

當我單擊一行中的按鈕時,該行(即數量)的輸入框中的值應為 0,並且“總價”列也應修改為 0。但這並沒有發生? 我應該添加什么?

qty不是object的鍵,將模型名稱更改為item.qty並從數組訪問它時,引用object index

注意:還要考慮[index]處的錯字,您接受參數為$index但在訪問密鑰時,使用index

建議: <input> type='number'更適合您的用例

 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>

小提琴演示

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM