【问题标题】:make a list of infos adding Id in angularjs列出在 angularjs 中添加 Id 的信息
【发布时间】:2016-04-07 02:21:08
【问题描述】:

我想列出输入姓名、工作的信息。这是一个包含这些输入的表单。单击保存按钮时输入名称和工作,它将添加到列表中。并查看它们。但我也想每次都添加 id 。我怎样才能做到这一点?

这是我的小伙伴:https://plnkr.co/edit/VDYYrxk8Bz5KIoI0HFV4?p=preview

HTML:

<body ng-controller='MyController'>

    <!-- <button ng-click='toggleForm()'>Upload</button> -->

    <div>
        <table class='table'>
            <tr>
                <th>Title</th>
                <th>Work</th>
            </tr>
            <tr  ng-repeat='info in infos'>
                <td>{{info.name}}</td>
                <td>{{info.work}}</td>
            </tr>
        </table>
    </div>
    <form class='form'>
        <div class='form-group'>
            <label>Name</label>
            <input class='form-control' type="text" ng-model='info.name'>
        </div>
        <div class='form-group'>
            <label>Work</label>
            <input class='form-control' type="text" ng-model='info.work'>
        </div>
        <div class='form-group'>
            <button class='btn btn-primary' ng-click='addInfos()'>Save</button>
        </div>
    </form>
  </body>

脚本::

angular
.module('app')
.controller('MyController', function($scope){

    // $scope.displayForm = false;
    // $scope.toggleForm = function(){
    //     $scope.displayForm = !$scope.displayForm;
    // };
    $scope.infos = [];
    // var currIndex = 0;
    $scope.addInfos = function () {
        $scope.infos.push({
            name: '',
            work: ''
            // id: currIndex++
        });
        // $scope.infos.push(obj.info);

    };
})

【问题讨论】:

  • 首先,您的 plunkr 引入了 Angular 2 库,但您正在创建一个 Angular 1 应用程序。我会从那里开始。

标签: angularjs


【解决方案1】:
$scope.addInfos = function () {
        $scope.infos.push({
            name: $scope.info.name,
            work: $scope.info.work,
            id: $scope.infos.length + 1 // assuming you want ids to start with 1
        });   
        $scope.info = {}; // to clear the form fields once an input is pushed to the array
    };

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-11-19
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多