简体   繁体   中英

angularjs creating dynamic form elements

I have my html elements like this:

<body ng-controller="addController">
<div class="col-sm-10">

    <label class="control-label">tableName:</label> 
    <fieldset ng-repeat="tableName in tableNames">

        <input type="text" class="form-control" ng-model="tableName.tableName" /><br />
    </fieldset>
    <button class="btn btn-default" ng-click="addNewTable()">Add tablename</button>
    <input type="submit" ng-click="add()" />    
</div>
<div>
   <pre>{{tableNames|json}}</pre> 
</div>
</body>

This code generates a text box every time button is clicked.

js:

function addController($scope, $http) {

        $scope.tableNames = [];
        $scope.addNewTable = function (tableName) {
            $scope.tableNames.push({});

        }
}

When i display tableNames it gives me:

[{"tableName":"textboxvalue"},{"tableName":"textboxvalue"}];

But what i intend is getting output of:

[{"tableName1":"textboxvalue","tableName2":"textboxvalue","tableName3":"textboxvalue"}];

What should I have to change in design in order to get desired output. Thanks in advance.

You're pushing objects to the array each time but what you want is to add key value pair in the object in the array. try this

 $scope.tableNames = [{}];
    $scope.addNewTable = function (tableName) {
        $scope.tableNames[0].tableName = "textboxvalue" ;

    }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM