John Abraham
John Abraham

Reputation: 18801

How to submit dropdown inputfield as an array in angular

Live Code -- JSBIN Link

I have a nested lists of javascript objects Templates.schema

There will be many sections per page and I must keep track of them (via an index).

How do I make sure on submit of form, that addPage() function creates an array on the section via input ng-model="pageAdder.page.section

<form ng-model="pageAdder" ng-submit="addPage()">
    <label for="page.name">PAGE</label>
    <input type="text" ng-model="pageAdder.page.name">
    <br>
    <hr>
    <label for="page.name">Section</label>

    <select id="s1" ng-model="pageAdder.page.section" ng-options="item as item.type for item in items"></select>

    <br>
    <hr>


    <input class="btn btn-primary" type="submit" value="add Page">
</form>

to...

templates: {
  "schema": [
    {
      "page": {
        "name": "asdfasdf",
        "section": [{
          "id": 1,
          "type": "foo"
        }]//adds array
      }
    }
  ]
}

controller

angular.module("ang6App")
    .controller("MainCtrl", function ($scope) {

    })
    .controller("templatesCtrl", function ($scope, Templates) {

      $scope.template = Templates;

      $scope.addPage = function() {
        $scope.template.schema.push($scope.pageAdder);

      };

      $scope.items = [
       { id: 1, type: 'foo' },
       { id: 2, type: 'bar' },
       { id: 3, type: 'blah' }];

      $scope.pageAdder = {


      };

//end of templates
});

Upvotes: 0

Views: 29

Answers (1)

Chen-Tsu Lin
Chen-Tsu Lin

Reputation: 23234

add default value to $scope.pageAdder

$scope.pageAdder = {
  "page": {
    "name": null,
    "section": [{
      "id": null,
      "type": null
    }]
}

And it works fine: http://jsbin.com/OGipAVUF/45/edit

Upvotes: 1

Related Questions