如何将动态文本框值分配给相应的模型

时间:2016-03-15 00:35:54

标签: javascript angularjs

在我的角度js应用程序中,用户可以动态添加文本框并更新数据。如何将这些映射到模态。这是我从当前用例中获得的一个简单问题。

    <tr ng:repeat="item in invoice.items">
        <td><input type="text" ng:model="personInfo.item.description"class="input-small"></td>           
        <td><input type="number" ng:model="personInfo.item.qty" ng:required class="input-mini"></td>
        <td><input type="number" ng:model="personInfo.item.cost" ng:required class="input-mini"></td>
        <td>{{item.qty * item.cost | currency}}</td>
        <td>
            [<a href ng:click="removeItem($index)">X</a>]
        </td>
    </tr>

http://jsfiddle.net/kiranmca04/d81fzLzf/1/

当用户提交页面时,我需要低于json格式。完整的html文件,你可以在jsfiddle中找到。

{信息:[        姓名:&#39; Albert&#39;,        年龄:&#39; 33&#39;,        items&#34;:[{&#34; desc&#34;:&#34; test1&#34;,&#34; qty&#34;:1,&#34; cost&#34;:33,},                  {&#34; desc&#34;:&#34; test2&#34;,&#34; qty&#34;:2,&#34; cost&#34;:4,},                  {&#34; desc&#34;:&#34; test3&#34;,&#34; qty&#34;:1,&#34; cost&#34;:1,}                ]
       ]    }

1 个答案:

答案 0 :(得分:1)

jsfiddle

根据您的代码,personInfo应该是单个对象,而不是数组

var personInfo = {
    items: []
}

$scope.addItem = function() {
    personInfo.items.push({
        qty: 1,
        description: '',
        cost: 0
    });
},
$scope.removeItem = function(index) {
    personInfo.items.splice(index, 1);
},

$scope.total = function() {
    var total = 0;
    angular.forEach(personInfo.items, function(item) {
        total += item.qty * item.cost;
    })

    return total;
}
$scope.personInfo = personInfo

$scope.saveData = function (personInfo)
{
    alert(JSON.stringify(personInfo));
    console.log('info '+JSON.stringify(personInfo));
}

<tr ng:repeat="item in personalInfo.items">
    <td><input type="text" ng:model="item.description"class="input-small"></td>           
    <td><input type="number" ng:model="item.qty" ng:required class="input-mini"></td>
    <td><input type="number" ng:model="item.cost" ng:required class="input-mini"></td>
    <td>{{item.qty * item.cost | currency}}</td>
...
相关问题