Create list of items of a single item at once

1.8k Views Asked by At

Angular task 1.5.x:

I have object like this:

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

I want a new object to be created in the above way with click of a single button. Note I dont want to add each item separately, all at once. Means, for a single object with name "a", I want to add all items for all days at once.

I can make it work but I want to know the correct way.

ultimately we should be able to create a javascript object in the above format(without id)(I think this format is correct) and send it to server so it will work. But how to add html/angular code so I will get an object that way.

Please let me know for more info.

2

There are 2 best solutions below

0
On BEST ANSWER

When using ng-model you do not have to fully define your object in order to have it constructed. E.g.:

Controller

$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>

The general structure must be defined beforehand, but you do not have to initialize all the properties. They will receive values when binding is triggered (view -> model).

2
On

You can do like this :

Create a button in your view and use ng-click directive to capture on click event.

Html:

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

Use angular.copy to create a deep copy of the source object.

This is what angular.copy does as explained in the docs :

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.

Controller:

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

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