我有一个特殊结构的机场工厂:
angApp.factory("Airports", function () {
var Airports = {};
Airports.detail = {
"PDX": {
"code": "PDX",
"name": "Portland International Airport",
"city": "Portland"
},
"STL": {
"code": "STL",
"name": "Lambert-St. Louis International Airport",
"city": "St. Louis"
},
"MCI": {
"code": "MCI",
"name": "Kansas City International Airport",
"city": "Kansas City"
}
};
return Airports;
});
与控制器关联: 如何编写适当的方法将输入推送到Airport.detail?
.controller("AirportsCtrl", function ($scope, Airports) {
$scope.formURL = "views/_form.html";
$scope.currentAirport = null;
$scope.airports = Airports;
$scope.setAirport = function (code) {
$scope.currentAirport = $scope.airports.detail[code];
};
$scope.addAirport = function() {
$scope.airports.push();
};
});
HTML:
我将什么投入到ng-model中以正确地将反对意见推送到Airport.details
添加机场
ID:
<div class="form-group">
<label >code:</label><br>
<input class="form-control" type="text" placeholder="eg. PDX">
</div>
<div class="form-group">
<label>Name:</label><br>
<input class="form-control" type="text" ng-model="" placeholder="eg. Portland Intl. Airport">
</div>
<div class="form-group">
<label>City</label><br>
<input class="form-control"type="text" ng-model="" placeholder="eg. Portland">
</div>
<input class="btn btn-primary" type="submit">
</form>
答案 0 :(得分:1)
有一些问题,但最大的阻碍是工厂正在定义一个对象,而不是一个数组。这就是推动不起作用的原因。
您需要从表单发送一些数据,因此我在HTML标记中绑定了表单元素的模型:
<form ng-submit="addAirport()" ng-model="ap" >
<h4 >Add Airport</h4>
<div class="form-group">
<label>ID:</label><br>
<input class="form-control" type="text" ng-model="ap.id" placeholder="eg. PDX">
</div>
为其他表单元素提供了匹配的模型,ap.code
,ap.name
和ap.city
。绑定顶级ap
对象稍后会保存一些代码。
addAirport
函数如下所示:
$scope.addAirport = function() {
$scope.airports.detail[$scope.ap.id] = $scope.ap;
delete($scope.ap);
};
只需将$scope.ap
(表单)数据添加到$scope.airports.detail
对象即可。 (详细对象包含集合)。 delete命令重置表单。
这是一个更新的jsbin,添加机场现在有效:http://jsbin.com/OGipAVUF/11/edit
答案 1 :(得分:1)
首先,将每个表单字段绑定到您的范围:
<div class="form-group">
<label >code:</label><br>
<input class="form-control" ng-model="code" type="text" placeholder="eg. PDX">
</div>
<div class="form-group">
<label>Name:</label><br>
<input class="form-control" type="text" ng-model="name" placeholder="eg. Portland Intl. Airport">
</div>
<div class="form-group">
<label>City</label><br>
<input class="form-control"type="text" ng-model="city" placeholder="eg. Portland">
</div>
然后,向详细信息对象添加新的哈希值:
$scope.addAirport = function() {
$scope.airports.detail[$scope.code] = {
code: $scope.code,
name: $scope.name,
city: $scope.city
}
});
某些基本验证是合适的,因此不会覆盖现有的“ID”。