请点击下面的链接。我正在Angular JS中创建一个选择框。
尽管选择框已成功填充,但当我选择任何选项时它会变空。虽然它应该显示所选的选项值。所有文件都可以在链接本身找到。
http://embed.plnkr.co/kBAyU1/preview
index.html
<!DOCTYPE html>
<html ng-app="shopping">
<head>
<meta charset="utf-8" />
<title>AngularJS Hello World</title>
<script>
document.write('<base href="' + document.location + '" />');
</script>
<link rel="stylesheet" href="style.css" />
<script data-require="angular.js@1.3.x" src="https://code.angularjs.org/1.3.14/angular.js" data-semver="1.3.14"></script>
<script src="app.js"></script>
</head>
<body ng-controller="ShoppingCtrl">
<h1>Oder till Now</h1>
<table>
<tr><td>Item Name</td><td>Quantity</td><td>Price</td><td>Total</td><td>Remove</td></tr>
<tr ng-repeat="item in items">
<td>{{item.name}}</td>
<td><input ng-model="item.quantity"></td>
<td>{{item.price |currency:'Rs'}}</td>
<td>Total: {{item.price * item.quantity | currency:'Rs'}}</td>
<td><button ng-click="remove($index)">Remove</button></td>
</tr>
</table>
<select ng-model="itemsList" ng-options="x.name for x in itemsList">
<option ng-if="!selectedItem" value="">Select item</option>
</select>
<!-- <input size="10" placeholder="quantity"/>
<input ng-model="itemList.price" size="10" placeholder="price"/> -->
<input class="btn-primary" type="button" value="add" ng-click="addItem()"/>
</body>
</html>
app.js
var app = angular.module('shopping',[]);
app.controller('ShoppingCtrl',function($scope){
$scope.items=[{
name: 'Lux Soap',
quantity: 10,
price: 120
},{
name: 'Panteene Shampoo',
quantity: 2,
price: 230
},{
name: 'Maggie',
quantity: 30,
price: 10
}];
$scope.itemsList =[{
name:'Shoe Polish',
price:40
},{
name:'Wine bottle',
price:1000
},{
name:'Lucky coin',
price:30
},{
name:'lunch box',
price:450
},{
name:'Tamatoo sauce',
price:100
},{
name:'Lux Soap',
price:120
},{
name:'Panteene Shampoo',
price:230
},{
name:'Maggie',
price:10
}];
$scope.remove = function(index){
$scope.items.splice(index,1);
};
$scope.addItem = function () {
$scope.items.push({
name: $scope.name,
quantity: $scope.quantity,
price: $scope.price
});
$scope.name = '';
$scope.quantity = '';
$scope.price = '';
};
});
答案 0 :(得分:1)
您选择的型号错误。它应该像
<select ng-model="itemsInList" ng-options="x.name for x in itemsList">
<option ng-if="!selectedItem" value="">Select item</option>
</select>
检查已修复的plnkr
答案 1 :(得分:1)
更改您的addItem
代码
JS
$scope.addItem = function () {
$scope.items.push({
name: $scope.selectedItemValue.name,
quantity: $scope.selectedItemValue.quantity,
price: $scope.selectedItemValue.price
});
$scope.selectedItemValue = '';//by doing this the ading functionality will get reset to previous state
$scope.selectedItemValue.quantity = '';
$scope.selectedItemValue.price = '';
};
和html选择代码和ng-model
名称
<select ng-model="selectedItemValue" ng-options="x.name for x in itemsList">
<option ng-if="!selectedItem" value="">Select item</option>
</select>