Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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).

I am getting this error when I try add more than one task.

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 answer and this blog post, which suggest adding track by $index, but it doesn't work properly for me...

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-repeat block I can see each task is now the same as the one I just added.

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?

Here is my 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:

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();
  };
});
like image 965
shrewdbeans Avatar asked Oct 03 '22 00:10

shrewdbeans


1 Answers

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:

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

In your 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.

like image 123
David Banister Avatar answered Oct 18 '22 13:10

David Banister