Angular JS - 拥有一个空数组

Jes*_*zie 1 html angularjs

我有一个表单,将数据提交到一个名为ng-submit="newBirthday()this 的函数中,将数据推 $scope.bdayname, $scope.bdaydate;送到一个名为的数组中bdaes

我的问题是,在我看到的所有教程中,数组都有预定义的数据,是否有一种方法可以是一个空数组,在提交数据时会被数据填充?

app.js:

var app = angular.module('birthdayToDo', []);

app.controller('main', function($scope){ 

    // Start as not visible but when button is tapped it will show as true 

        $scope.visible = false;

    // Create the array to hold the list of Birthdays

        $scope.bdays = [{}];

    // Create the function to push the data into the "bdays" array

    $scope.newBirthday = function(){

        $scope.bdays.push({name:$scope.bdayname, date:$scope.bdaydate});

        $scope.bdayname = '';
        $scope.bdaydate = '';

    }
});
Run Code Online (Sandbox Code Playgroud)

HTML:

<body ng-app="birthdayToDo" ng-controller="main">
    <div id="wrap">

      <!-- Begin page content -->
      <div class="container">
        <div class="page-header">
          <h1>Birthday Reminders</h1>
        </div>
            <ul ng-repeat="bdays in bdays">
                <li>{{bdae.name}} | {{bdae.date}}</li>
            </ul>

           <form ng-show="visible" ng-submit="newBirthday()">
            <label>Name:</label>
            <input type="text" ng-model="bdayname" placeholder="Name"/>
            <label>Date:</label>
            <input type="date" ng-model="bdaydate" placeholder="Date"/>
            <button class="btn" type="submit">Save</button>
        </form>
      </div>

      <div id="push"></div>
    </div>

    <div id="footer">
      <div class="container">
        <a class="btn" ng-click="visible = true"><i class="icon-plus"></i>Add</a>
      </div>
    </div>
        <script type="text/javascript" src="js/cordova-2.5.0.js"></script>
        <script type="text/javascript">
            app.initialize();
        </script>
    </body>
Run Code Online (Sandbox Code Playgroud)

Jos*_*ler 11

好的,有一些小问题.

  1. 空数组必须没有项目; [{}]是一个包含一个项目的数组:一个空对象.改变以[]摆脱额外的子弹.
  2. 更大的问题是你的ngRepeat.你用过ng-repeat="bdays in bdays".ngRepeat所做的是获取一个数组,并允许您对数组执行"for each",将每个值分配给该临时局部变量.你把它们命名为相同.相反,ng-repeat="bday in bdays"将为其中的每个项添加其中的DOM节点bdays,为您提供一个名为bday用于引用每个项的局部变量.
  3. 在您使用的ngRepeat模板中,bdae它没有引用任何内容.
  4. 我不知道是什么app.initialize(),所以我删除了它.它只是在控制台中出错了.

这是一个固定的Plunker:http://plnkr.co/edit/OFWY7o?p = preview