一次创建单个项目的项目列表

Create list of items of a single item at once

Angular 任务 1.5.x:

我有这样的对象:

{
    id: 1,
    name: "a",
    items: [
        {"holiday": "false", "day": "monday"}, 
        {"holiday": "true", "day": "tuesday"...}
    ]
}

我想通过单击一个按钮以上述方式创建一个新对象。注意我不想一次单独添加每个项目。意思是,对于名称为 "a" 的单个对象,我想一次性添加所有日期的所有项目。

我可以让它工作,但我想知道正确的方法。

最终我们应该能够以上述格式(不带 id)创建一个 javascript 对象(我认为这种格式是正确的)并将其发送到服务器,这样它就可以工作了。但是如何添加 html/angular 代码,这样我才能得到一个对象。

请让我知道更多信息。

你可以这样做:

在您的视图中创建一个按钮并使用 ng-click 指令捕获点击事件。

Html:

<button ng-click="createCopy()"></button>

使用angular.copy创建源对象的深拷贝。

这就是 angular.copy 所做的,如文档中所述:

Creates a deep copy of source, which should be an object or an array.

If no destination is supplied, a copy of the object or array is created. If a destination is provided, all of its elements (for arrays) or properties (for objects) are deleted and then all elements/properties from the source are copied to it. If source is not an object or array (inc. null and undefined), source is returned. If source is identical to destination an exception will be thrown.

控制器:

$scope.mainObject = { id: 1, name: "a", items: [{"holiday": "false", "day": "monday"}, {"holiday": "true", "day": "tuesday"...}] };

$scope.createCopy = function (){    
  $scope.copyObject = angular.copy($scope.mainObject);
}

使用 ng-model 时,您不必完全定义对象即可构造它。例如:

控制器

$scope.object= {
    items: [] 
};

var n = 7;
for (var i = 0; i < n; i++)
    $scope.object.items({});

HTML

<input type="text" ng-model="object.name"/>

<div ng-repeat="currObj in object.items">
    <input type="text" ng-model="currObj.holiday" />
    <input type="text" ng-model="currObj.day" />
</div>

一般结构必须预先定义,但您不必初始化所有属性。他们将在触发绑定时接收值(视图 -> 模型)。