将克隆的元素添加到 ng-repeat
Add cloned element to ng-repeat
我知道为了能够在 ng-repeat
中添加 "duplicates",您使用 track by
,但这对我来说不起作用
我有以下 ng-repeat 指令:
<div class="well" ng-repeat="surveyData in surveyDatas track by $index">
我的用户可能想向该列表添加一个新的 SurveyData,它们之间的差异可能只是 50 个字段中的一个,因此克隆它是理想的解决方案,所以我尝试这样做:
DOM:
<button class="btn-sm btn-danger margin10" ng-click="cloneSurveyData(surveyData)">Clone Survey Data:</button>
控制器:
$scope.cloneSurveyData = function (surveyData){
surveyData.id = null;
$scope.surveyDatas.push(surveyData);
};
但是,当然,我得到:
Error: [ngRepeat:dupes] Duplicates in a repeater are not allowed. Use 'track by' expression to specify unique keys. Repeater: surveyData in surveyDatas | orderBy:'id', Duplicate key: object:150
我试过通过 id 进行跟踪,并在控制器中创建一个变量,然后将其与 SurveyData 相等,没有什么
创建新变量并均衡所有字段是我唯一的选择吗?
尝试使用 angular.copy 将调查数据复制到 tmp 变量,然后将其推送到数组:
$scope.cloneSurveyData = function (surveyData){
var temp = angular.copy(surveyData);
temp.id = null;
$scope.surveyDatas.push(temp);
};
编辑:
作为解释,我希望这会有所帮助:
您的示例代码中没有 order by
,但错误文本中有它:
Repeater: surveyData in surveyDatas | orderBy:'id', Duplicate key: object:150
使用您的代码,您只创建了一个引用并将其推送到数组。所以 orderBy
试图用完全相同的对象 id 来排序两个对象。
我知道为了能够在 ng-repeat
中添加 "duplicates",您使用 track by
,但这对我来说不起作用
我有以下 ng-repeat 指令:
<div class="well" ng-repeat="surveyData in surveyDatas track by $index">
我的用户可能想向该列表添加一个新的 SurveyData,它们之间的差异可能只是 50 个字段中的一个,因此克隆它是理想的解决方案,所以我尝试这样做:
DOM:
<button class="btn-sm btn-danger margin10" ng-click="cloneSurveyData(surveyData)">Clone Survey Data:</button>
控制器:
$scope.cloneSurveyData = function (surveyData){
surveyData.id = null;
$scope.surveyDatas.push(surveyData);
};
但是,当然,我得到:
Error: [ngRepeat:dupes] Duplicates in a repeater are not allowed. Use 'track by' expression to specify unique keys. Repeater: surveyData in surveyDatas | orderBy:'id', Duplicate key: object:150
我试过通过 id 进行跟踪,并在控制器中创建一个变量,然后将其与 SurveyData 相等,没有什么
创建新变量并均衡所有字段是我唯一的选择吗?
尝试使用 angular.copy 将调查数据复制到 tmp 变量,然后将其推送到数组:
$scope.cloneSurveyData = function (surveyData){
var temp = angular.copy(surveyData);
temp.id = null;
$scope.surveyDatas.push(temp);
};
编辑:
作为解释,我希望这会有所帮助:
您的示例代码中没有 order by
,但错误文本中有它:
Repeater: surveyData in surveyDatas | orderBy:'id', Duplicate key: object:150
使用您的代码,您只创建了一个引用并将其推送到数组。所以 orderBy
试图用完全相同的对象 id 来排序两个对象。