【问题标题】:How to assign dynamic text box values to corresponding models如何将动态文本框值分配给相应的模型
【发布时间】:2016-03-15 00:35:53
【问题描述】:

在我的 Angular 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 格式。您可以在 jsfiddle 中找到完整的 html 文件。

{信息:[ 名称:“阿尔伯特”, 年龄:'33', 项目”:[ {“desc”:“test1”,“数量”:1,“成本”:33,}, {“desc”:“test2”,“数量”:2,“成本”:4,}, {“desc”:“test3”,“数量”:1,“成本”:1,} ]
] }

【问题讨论】:

    标签: javascript angularjs


    【解决方案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>
    ...
    

    【讨论】:

    • 嗨.. 根据您的建议,我已经更改了它,但我在警报中变得未定义。这是链接jsfiddle.net/ga8spqm5/3你能看一下吗
    • jsfiddle.net/awakeningbyte/b25xo3Lw/1 您需要将personalInfo 传递给saveData 函数。 ng-click="saveData(personInfo)" 在第 36 行
    • 成功了,谢谢。如果你不认为这是一个愚蠢的问题。我看到请求中的每一行都有另一个字段 "$$hashKey":"008" 这是什么?
    • 它是通过角度添加的。我已经更新了示例代码。将 JSON.stringify 更改为 angular.toJson() 。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2012-05-31
    • 2012-01-03
    • 2021-07-25
    • 2021-05-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多