Search code examples
angularjsobject-initialization

Create list of items of a single item at once


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.


Solution

  • 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).