user16655 user16655 - 6 months ago 23
HTML Question

Ng-repeat -how to avoid copying input content of div

I am duplicating a

by using
. When a button is clicked, a new but duplicated
element appear. The problem is that the user can add tasks in the list, and when I duplicate the div, it also duplicates the content. Here is my html which is repeated:

<div class="row">
<div class="col" ng-repeat="input in inputs track by $index">
<div class="task-container">
<div class="content-task-container">
<div class="row">
<div class="input-field col s10">
<input id="task-input-{{$index}}" type="text" ng-model="task">
<label for="task-input-{{$index}}">Write task here</label>
<div class="btn-add">
<a class="btn-floating" id="btn-add-task"><i class="material-icons" ng-click="addTask(task)">add</i></a>
<div class=show-tasks ng-repeat="task in tasks track by $index">
<input type="checkbox" id="task-{{$index}}"/>
<label for="task-{{$index}}">{{task}}</label>

Here is the controller that both handles the adding of tasks in the list, and the duplication of the div element:

app.controller('listCtrl', function($scope, $routeParams) {
$scope.owner = $routeParams.owner;

$scope.task = "";

$scope.tasks = [];

$scope.addTask = function(task) {
$scope.task = "";

$scope.inputCounter = 0;
$scope.inputs = [{
id: 'input'

$scope.cloneContainer = function() {
console.log("inside cloneContainer()")
$scope.inputTemplate = {
id: 'input-' + $scope.inputCounter,
name: ''
$scope.inputCounter += 1;


I've tried to give all the id elements an unique id, but this doesn't cut it. I also need the 'tasks' array to be unique for each div element in
. Is there any way to achieve this?

A simple plunkr to illustrate the problem:


The way you're conceptualizing this is a bit off -- don't think in terms of duplicating DOM nodes. Instead think in terms of modifying your data model, each part of which happens to be rendered as a different DOM node.

In this case, you put all your data into a single shared controller, with a single "task" array; when you tried to create a new task list it wound up referring to the same task array and therefore appeared to be a duplicate of the original list. (In fact it was a separate list, but referencing the same data from $scope.tasks.)

Here the controller contains $scope.lists[], each element of which is itself an array of tasks:

app.controller('MainCtrl', function($scope) {
  $scope.lists = [];
  $scope.addList = function() {
    $scope.lists.push([]); // start each new task list with an empty array

app.directive('taskList', function() {
  return {
    scope: {
      mylist: '=taskList' 
    templateUrl: 'tasklist.html',
    link: function(scope) {
      scope.addTask = function() {
        scope.newtask = '';

You can see this in action here: