在数组中添加和显示新对象的函数

Function to add and show up a new object in an array

我刚开始玩 AngularJS,我想构建一个应用程序,它只添加另一个人的名字和 his/her 出生日期。 我已经有了初始数据(2 人和他们的出生日期 (dob))。 通过写下全名和出生日期,然后按添加按钮,我想添加另一个人以及 his/her 出生日期 - 这个新人也应该在列表中列出并可见。

到目前为止,我使该函数创建了一个新对象。但不幸的是,我无法以正确的方式将输入数据与新添加的对象组合起来。 有人可以帮我吗?也许有更简单的方法

到目前为止我创建了这个:

<html>
    <head>
        <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.6.9/angular.min.js"></script>
    </head>
    <body>
        <script>
            var app = angular.module("myBirthApp",[]);
            app.controller("myCtrl", function($scope){
               $scope.birthdays=[
                {fullName:'Jane Doe', dateOfBirth:'08.03.1990'}, 
                {fullName:'John Doe', dateOfBirth:'19.11.1995'}];
                    // create new array with addItem!
                    $scope.addItem = function () {
                    $scope.birthdays.push($scope.addMe);
                    }
                });
                    
        </script>
        <div ng-app="myBirthApp" ng-controller="myCtrl">
            <ul>
                <li ng-repeat="x in birthdays"><p>Name: {{x.fullName}}</p> <p>Date of birth: {{x.dateOfBirth}}</p> </br></li>
            </ul>
            <form>
                <fieldset>
                    <legend>Add a person</legend>
                First name and last name: <input type="text" ng-model="fullName"></br>
                Date of birth: <input type="date" ng-model="dateOfBirth"></br>
                <button ng-click="addItem()">Add</button>
                </fieldset>
            </form>
        </div>
    </body>
</html>

您可以声明一个变量:

$scope.person = {
    fullName: '',
    dateOfBirth: null
};

并将其绑定到 ngModel 输入:

<input type="text" ng-model="person.fullName"><br />
<input type="date" ng-model="person.dateOfBirth">

然后在 addItem 方法中将其推送到 birthdays 数组。 (当然还需要进一步添加、验证检查等,但这是基本思想)

在此处查看工作演示:DEMO