【问题标题】:how to create a new instance of the object for ng-repeat如何为 ng-repeat 创建对象的新实例
【发布时间】:2023-03-24 19:55:02
【问题描述】:

如何为 ng-repeat 创建具有不同(唯一)hashkey 或 id 的对象的新实例?我尝试使用“track by”,但无法使用。

我的代码如下:

对于表中的每一行(可能是 5 ,10 ...行),我想显示存储在此列表中的同一组复选框:

    $scope.list_of_checkboxes = 
[
    {
      name: "ch1",
      properties:[{t:"text1",v:0},{t:"text2",v:0},{t:"text3",v:0}]
    },
     {
      name: "ch2",
      properties:[{t:"text1",v:0},{t:"text2",v:0},{t:"text3",v:0}]
    }
 ];

选中复选框后,我将使用此库将复选框对象存储在 $scope.table_rows.objects 中: http://vitalets.github.io/checklist-model/

$scope.table_rows=[{row_1:'row # 1', objects:[]},{row_2: 'row # 2',objects:[]},{row3:'row # 3',objects:[]}]

复选框显示并正常运行。但是,当我将选中复选框的对象存储在 $scope.table_rows.objects 中时,它们都具有相同的 hashkey。这就是问题。因为,当我显示 properties:[{t:"text1",v:0},{t:"text2",v:0},{t:"text3",v:0}] 作为输入字段并更新属性值之一,例如 table_rows[key].objects[1].v = 30,将相同的值复制到存储在其他行中的同一对象的属性中。

我尝试返回新实例(但它不起作用):

$scope.list_of_checkboxes = function (){ 

 return ([
    {
      name: "ch1",
      properties:[{t:"text1",v:0},{t:"text2",v:0},{t:"text3",v:0}]
    },
     {
      name: "ch2",
      properties:[{t:"text1",v:0},{t:"text2",v:0},{t:"text3",v:0}]
    }
 ])
}

【问题讨论】:

  • 请正确格式化您的代码;很难弄清楚什么是问题文本,什么是代码。

标签: javascript html angularjs angularjs-ng-repeat angularjs-track-by


【解决方案1】:

不是完整的实现,但您可以尝试使用 track by $id(obj) :

HTML:

<div ng-app="myApp" ng-controller="Ctrl">
<table>
    <tr ng-repeat=" row in rows track by row.name">
<td ng-repeat="role in roles track by $id(role)" >
  <input type="checkbox" checklist-model="user.roles" checklist-value="$id"/> {{role.name}},{{$id}}
        </td>
        </tr>
</table>
<br><br><br>
user.roles {{ user.roles | json }}
</div>

JavaScript:

var app = angular.module("myApp", ["checklist-model"]);

app.controller('Ctrl', function($scope) {
$scope.rows=[{
    name:'first'
},{
    name:'second'
},{
    name:'third'
}];
$scope.roles =[
{
  name: "ch1"
},
 {
  name: "ch2"    }
];

$scope.user = {
roles: []
};
});

演示:http://jsfiddle.net/FC9c7/78/

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-01-02
    • 1970-01-01
    • 2020-06-18
    • 2017-04-25
    相关资源
    最近更新 更多