我正在使用<div>
复制ng-repeat
。单击按钮时,会出现一个新的但重复的<div>
元素。问题是用户可以在列表中添加任务,当我复制div时,它也会复制内容。这是我的html重复:
<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>
<div class="btn-add">
<a class="btn-floating" id="btn-add-task"><i class="material-icons" ng-click="addTask(task)">add</i></a>
</div>
</div>
<div class=show-tasks ng-repeat="task in tasks track by $index">
<p>
<input type="checkbox" id="task-{{$index}}"/>
<label for="task-{{$index}}">{{task}}</label>
</p>
</div>
</div>
</div>
</div>
</div>
这是控制器,它既处理列表中的任务添加,又复制div元素:
app.controller('listCtrl', function($scope, $routeParams) {
$scope.owner = $routeParams.owner;
$scope.task = "";
$scope.tasks = [];
$scope.addTask = function(task) {
console.log(task);
$scope.tasks.push(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;
$scope.inputs.push($scope.inputTemplate);
};
});
我试图给所有id元素一个唯一的ID,但这并没有削减它。我还需要&#39;任务&#39;数组在ng-repeat
中对每个div元素都是唯一的。有没有办法实现这个目标?
一个简单的插图来说明问题:http://plnkr.co/edit/LtWXUG6MKU5TGFTXpWUn?p=preview
答案 0 :(得分:1)
您对此概念化的方式有点偏离 - 不要考虑重复DOM节点。相反,考虑修改数据模型,其中每个部分恰好都呈现为不同的DOM节点。
在这种情况下,您将所有数据放入一个共享控制器中,并使用一个“任务”数组;当你试图创建一个新的任务列表时,它会引用相同的任务数组,因此看起来是原始列表的副本。 (实际上它是一个单独的列表,但引用了$scope.tasks
中的相同数据。)
这里控制器包含$scope.lists[]
,其中每个元素本身就是一个任务数组:
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.mylist.push(scope.newtask);
scope.newtask = '';
};
}
};
});
您可以在此处查看此操作:http://plnkr.co/edit/jP3LGacZMox9o55uHffm?p=preview
或者,您可以将任务数据完全保留在控制器之外,并仅将其存储在指令中。 (我倾向于尽可能使用这种方法,仅使用控制器来处理需要在多个指令之间共享的数据或功能):
app.controller('MainCtrl', function($scope) {
$scope.lists = [];
$scope.addList = function() {
$scope.lists.push(""); // here we only care about the length of the array, its content is irrelevant
};
});
app.directive('taskList', function() {
return {
templateUrl: 'tasklist.html',
link: function(scope) {
scope.mylist = []; // mylist is not passed in from the controller, so init it here. Each instance of the directive will have its own mylist array
scope.addTask = function() {
scope.mylist.push(scope.newtask);
scope.newtask = '';
};
}
};
});