javascript Angular.js 错误:不允许在中继器中重复 - 按索引跟踪无法按预期工作

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/20883133/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-27 19:32:24  来源:igfitidea点击:

Angular.js Error: Duplicates in a repeater are not allowed - Track by index doesn't work as intended

javascriptangularjs

提问by shrewdbeans

I am going through a tutorial on the Ionic Framework, which is using Angular JS to create a simple Todo app. It creates a new task by using .push()to append a new task object onto an array of task objects (code is below).

我正在阅读有关Ionic Framework的教程,该教程使用 Angular JS 创建一个简单的 Todo 应用程序。它通过使用.push()将新任务对象附加到任务对象数组来创建新任务(代码如下)。

I am getting this error when I try add more than onetask.

当我尝试添加多个任务时出现此错误。

Error: [ngRepeat:dupes] Duplicates in a repeater are not allowed. Use 'track by' expression to specify unique keys. Repeater: task in tasks, Duplicate key: object:00C
http://errors.angularjs.org/1.2.4/ngRepeat/dupes?p0=task%20in%20tasks&p1=object%3A00C

I've tried using the solution as posted in this answerand this blog post, which suggest adding track by $index, but it doesn't work properly for me...

我已尝试使用此答案此博客文章中发布的解决方案,建议添加track by $index,但它对我来说无法正常工作...

It does get rid of the error, but then when I add a new task it updates all of the objects in the array with that new task! And in my list of tasks within the ng-repeatblock I can see each task is now the same as the one I just added.

它确实消除了错误,但是当我添加一个新任务时,它会使用该新任务更新数组中的所有对象!在ng-repeat块内的任务列表中,我可以看到每个任务现在都与我刚刚添加的任务相同。

What am I doing wrong here? Is it something to do with the objects that I'm pushing onto the array? I am new to Angular.js so perhaps I am missing something simple yet crucial?

我在这里做错了什么?这与我推到阵列上的对象有关吗?我是 Angular.js 的新手,所以也许我错过了一些简单但至关重要的东西?

Here is my HTML:

这是我的 HTML:

<body ng-app="todo" ng-controller="TodoCtrl">
  <side-menus>

    <!-- Center content -->
    <pane side-menu-content>
    <header class="bar bar-header bar-dark">
      <h1 class="title">Todo</h1>
      <!-- New Task button-->
      <button class="button button-icon" ng-click="editTasks()">
        <i class="icon ion-edit"></i>
      </button>
      <button class="button button-icon" ng-click="newTask()">
        <i class="icon ion-compose"></i>
      </button>
    </header>
      <content has-header="true">
        <!-- our list and list items -->
        <list>
          <item ng-repeat="task in tasks track by $index">
            {{task.title}}
          </item>
        </list>
      </content>
    </pane>

    <!-- Left menu -->
    <side-menu side="left">
      <header class="bar bar-header bar-dark">
        <h1 class="title">Projects</h1>
      </header>
    </side-menu>

    <!-- Add a new task -->
        <script id="new-task.html" type="text/ng-template">         
          <div class="modal">   
            <!-- Modal header bar -->
            <header class="bar bar-header bar-secondary">
              <h1 class="title">New Task</h1>
              <button class="button button-clear button-positive" ng-click="closeNewTask()">Cancel</button>
            </header>
            <!-- Modal content area -->
            <content has-header="true">     
              <form ng-submit="createTask(task)">
                <div class="list">
                  <label class="item item-input">
                    <input type="text" placeholder="What do you need to do?" ng-model="task.title">
                  </label>
                </div>
                <div class="padding">
                  <button type="submit" class="button button-block button-positive">Create Task</button>
                </div>
              </form>
            </content>
          </div>        
        </script>       

  </side-menus>
</body>

And here is my JS:

这是我的 JS:

angular.module('todo', ['ionic'])

.controller('TodoCtrl', function($scope, Modal) {
  // No need for testing data anymore
  $scope.tasks = [];

  // Create and load the Modal
  Modal.fromTemplateUrl('new-task.html', function(modal) {
    $scope.taskModal = modal;
  }, {
    scope: $scope,
    animation: 'slide-in-up'
  });

  // Called when the form is submitted
  $scope.createTask = function(task) {
    console.log('task', task);
    $scope.tasks.push(task);
    console.log('$scope.tasks', $scope.tasks);
    $scope.taskModal.hide();
  };

  // Open our new task modal
  $scope.newTask = function() {
    $scope.taskModal.show();
  };

  // Close the new task modal
  $scope.closeNewTask = function() {
    $scope.taskModal.hide();
  };
});

采纳答案by David Banister

The problem looks like you are not creating independent task instances. It appears that your modal is binding to a single task instance and attempting to add the same exact reference each time. Try something like the following.

问题看起来像您没有创建独立的任务实例。看来您的模态绑定到单个任务实例并尝试每次添加相同的精确引用。尝试类似以下内容。

In your JS:

在你的 JS 中:

// Open our new task modal
$scope.newTask = function() {
   $scope.editTask = {};
   $scope.taskModal.show();
};

In your HTML:

在您的 HTML 中:

   <form ng-submit="createTask(editTask)">
      <div class="list">
         <label class="item item-input">
            <input type="text" placeholder="What do you need to do?" ng-model="editTask.title">
         </label>
      </div>
      <div class="padding">
         <button type="submit" class="button button-block button-positive">Create Task</button>
      </div>
   </form>

That creates a new editTask instance every time the newTask function is called and adds that new instance to the array. You should not need the track by $index code after those changes.

每次调用 newTask 函数时都会创建一个新的 editTask 实例,并将该新实例添加到数组中。在这些更改之后,您应该不需要 $index 代码的跟踪。