我想在Angularjs中创建json对象。当addBasket上添加新的篮子对象添加到数组时,单击addOrder时添加新的顺序到数组。事实上,日期字段不会在循环中重复。 dothis方式很好创建json对象?或者可能存在创建json对象的良好解决方案。
编辑问题:
我想以json格式创建对象。我把格式放在下面。我写了我已经说过的代码。实际上,我的问题是在orders数组中添加一个对象。如何将新对象添加到订单数组?
[
{
"date":'2015-30-7',
"baskets": [
{
"orders": [
{
"id": "12"
}
],
"customer": {
"phone": "555555"
},
"discount": "8"
}
]
}
]
var app = angular.module('app', []);
app.controller('myController', function($scope, $http) {
$scope.typistData = [];
$scope.typistData.push({
baskets: [{
orders:[]
}]
});
$scope.addBasket = function() {
$scope.typistData.push({
baskets: [{
orders:[]
}]
});
};
});

<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<div ng-app='app' ng-controller='myController'>
<input type="text" ng-model="data.name">
<hr>
<div ng-repeat="data in typistData" ng-if="typistData">
<form novalidate ng-submit="submitOffices()">
<div>
<ng-form ng-repeat="basket in data.baskets">
<div>
<input type="text" ng-model="basket.customer.phone">
<br>
<input type="text" ng-model="basket.discount">
<input type="text" ng-model="basket.orders[0].id">
<input type="button" value="addOrder">
</div>
<hr>
</ng-form>
</div>
</form>
</div>
<button ng-click="addBasket()">Add Basket</button>
<div>
<pre>{{ typistData | json }}</pre>
</div>
</div>
&#13;
答案 0 :(得分:1)
根据我从您的问题中所理解的,您希望能够在任何打字员的篮子中添加一个篮子,并且您还想要为其中一个打字员的一个篮子的订单添加订单。
对于处理,我认为你可以通过ng-click传入addBasket和addOrder在ng-repeat中的正确对象(它可以工作,因为它传递了引用)。所以可能的工作变化是:
查看部分:
<div ng-repeat="data in typistData" ng-if="typistData">
<form novalidate ng-submit="submitOffices()">
<div>
<ng-form ng-repeat="basket in data.baskets">
<div>
<input type="text" ng-model="basket.customer.phone">
<br>
<input type="text" ng-model="basket.discount">
<input type="text" ng-model="basket.orders[0].id">
<!-- Here you call the addOrder with basket. -->
<button ng-click="addOrder(basket)">Add Order</button>
</div>
<hr>
</ng-form>
<!-- Here you call the addBasket with data. .-->
<button ng-click="addBasket(data)">Add Basket</button>
</div>
</form>
</div>
控制器部分:
var app = angular.module('app', []);
app.controller('myController', function($scope, $http) {
$scope.typistData = [];
$scope.typistData.push({
baskets: [{
orders:[]
}]
});
/* This is wrong, because it doesn't add a basket, instead it
another typist's details.
$scope.addBasket = function() {
$scope.typistData.push({
baskets: [{
orders:[]
}]
});
Correct way of adding it is to use the passed in reference to the
data of a particular typist, and add a basket to its baskets.
*/
$scope.addBasket = function(typist) {
// Adding a basket to the typist's baskets, and you want the
// basket to contain an empty orders array initially right.
typist.baskets.push({
orders:[]
});
};
// To add an order to one of the basket of the baskets of a
// particular typist.
$scope.addOrder = function(typistBasket) {
typistBasket.orders.push({
// Whatever you want the order to have.
});
};
});