Angular。将数组推入数组

Angular. Push array in array

我尝试使用 Angular.js 做 TODO 列表 我有函数 addTask,但它不起作用。我尝试给它项目,而不是获得一系列任务。在 Chrome 我看到这个错误 "Cannot read property 'tasks' of undefined" 这是我的app.js

    var app = angular.module('toDoList', ['ngDialog']);
        app.controller('MainCtrl', [
          '$scope',
          '$rootScope',
          'ngDialog',
          function($scope, $rootScope, ngDialog){
      $scope.test = 'Hello world!';

    $scope.projects = [
      {id: '1', title: 'For Home', tasks: [ {title: 'task 1', done:false }, {title: 'task 2', done: false }]},
      {id: '2', title: 'For Work', tasks: [ {title: 'task 1', done:false }, {title: 'task 2', done: false }]}
    ];

    $scope.addProject = function(){
      if(!$scope.title || $scope.title === '') { return; }
      $scope.projects.push({
        title: $scope.title
      });
    };

    $scope.addTask = function(project){

      $scope.project.tasks.push({
        title: $scope.tasktitle, done: false
      });
}]);

这是我的html代码

    <body ng-app="toDoList" ng-controller="MainCtrl">
  <div class="project" ng-repeat="project in projects">
    <span class="title">{{project.title}}</span>
      <form name="frm" ng-submit="addTask(project)">
        <input 
          type="text" 
          class="form-control" 
          placeholder="Start to type task"
          ng-model="tasktitle">
        <span class="input-group-btn">
          <button class="btn btn-default" type="submit">Add Task</button>
        </span>
      </form>
    <ul class="todo-list">             
      <li ng-repeat="task in project.tasks">
        <input type="checkbox" ng-model="task.done">
        <span ng-class="{done:task.done}">{{task.title}}</span>
      </li>
    </ul>
  </div>
</body>

如何推送我的任务数据?

这是行不通的:

$scope.addTask = function(project){

  $scope.project.tasks.push({
    title: $scope.tasktitle, done: false
  });

};

首先,您在 $scope.project.tasks.push 中缺少 's'。它应该是 projects,以便与范围变量匹配。

其次,您实际上并没有选择要推送的项目。 $scope.projects 是一个数组。您需要选择要推送到的索引。这就是我认为你想要的:

HTML

<form name="frm" ng-submit="addTask(project.id, tasktitle)">

Javascript

$scope.addTask = function(id, task){

  $scope.projects[id].tasks.push({
    title: task
    , done: false
  });

};

编辑:工作代码笔在:codepen.io/Pangolin-/pen/YPVwye – Pangolin

我可以解决这个问题,但我不知道这样做对吗?

HTML

<form name="frm" ng-submit="addTask(project.tasks, tasktitle)" class="input-group">

Javascript

   $scope.addTask = function(project, value){
   project.push({
    title: value
  });