我是棱角分明的新手,在设置它时遇到了一些麻烦。如何设置表单和控制器以将新对象推入现有数组?
的index.html:
<html ng-app="gemApp">
<div ng-controller="storeController as store">
<h3>Gems</h3>
<div ng-repeat="item in store.products" | orderBy:"name">
<h5>{{item.name}}</h5>
<h5>{{item.price | currency}}</h5>
</div>
</div>
app.js:
var app = angular.module("gemApp", []);
app.controller("storeController", storeController)
function storeController(){
this.products = gems;
}
var gems = [
{ name: 'Azurite', price: 2.95 },
{ name: 'Bloodstone', price: 5.95 },
{ name: 'Zircon', price: 3.95 }
];
答案 0 :(得分:2)
这是你如何做到的一个非常基本的样本。请记住,我省略了验证等,并且此处存储的数据只保存在内存中。要及时存储,您必须将其保存到数据库中。
<强>段强>
var app = angular.module("gemApp", []);
app.controller("storeController", storeController)
function storeController() {
var self = this;
self.products = gems;
self.current = {};
this.add = function() {
gems.unshift(angular.copy(self.current));
self.current = {};
}
}
var gems = [{
name: 'Azurite',
price: 2.95
},
{
name: 'Bloodstone',
price: 5.95
},
{
name: 'Zircon',
price: 3.95
}
];
&#13;
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<div ng-app="gemApp" ng-controller="storeController as store">
<form>
<label>Name</label>
<input type="text" ng-model="store.current.name">
<br>
<label>Price</label>
<input type="number" ng-model="store.current.price">
<br>
<input type="button" value="Guardar" ng-click="store.add()">
</form>
<h3>Gems</h3>
<div ng-repeat="item in store.products" | orderBy: "name">
<h5>{{item.name}}</h5>
<h5>{{item.price | currency}}</h5>
</div>
</div>
&#13;