3

在我的应用程序中,我有一个ItemsService从服务器获取项目并将它们作为 JSON 对象存储在其cache变量中的。项目可以出现在许多地方,例如表格或图形/图表等。

例如,当我初始化 a table- 我只需要从中选择特定项目cache,例如 1st、3rd、7th。

如何实现它们之间的双向连接?基本上我想table包含对特定项目的引用,cache因此当我更改项目时cachetable它的状态将一直保持同步,因为它是同一个项目。

此外,当我从中删除项目时table- 它需要从cache. 缓存与表的关系

这是tablecache结构的示例:

桌子:

table: {
    "36": { // it's a name of a row
        "72": [items], // it's a name of a column with corresponding items
        "73": [items],
        "74": [items]
    },

    "37": {
        "72": [],
        "73": [items],
        "74": [items]
    },
    "38": {
        "72": [],
        "73": [],
        "74": []
    }
}

ItemsService 缓存(简化版):

ItemsService = {
  cache: [items]
};

物品结构:

{
  id: 3,
  parent_id: 1, 
  name: 'First Item', 
  siblings: [1,2,3],
  active_users: [{user_id: 1, avatar_url: 'http://...'}, ...],
  // 50 more fields :)
}

还需要指出我使用angular-ui-sortable插件来允许在列/行之间拖动项目,并且我需要提供ng-model数组(我认为)。这是它现在的样子:

<td ui-sortable="vm.sortableOptions"
    ng-model="vm.table[row.id][column.id]">
  <sb-item itemid={{item.id}} 
           ng-repeat="item in vm.table[row.id][column.id]">
  </sb-item>
</td>
4

3 回答 3

1

你最好的选择是对象。在 javascript 中保存对象的变量并不是真正保存对象,而是对所述对象的引用。当您将该变量传递给另一个变量时,引用值将被复制,因此两个变量都指向同一个对象。

var a = { 0: 'Property 0' };
var b = a;
b[0] = 'Property 0!'; //a[0] also the same.
delete b[0]; //a[0] nor b[0] exist anymore.
于 2015-09-27T14:07:29.533 回答
1

除非由于某种原因您必须使用两个单独的数组,否则您是否考虑过使用过滤器

于 2015-09-27T14:08:00.380 回答
0

使用对象(而不是 JSON)会起作用。

然后你的缓存和你的表都指向相同的项目对象。如果您更改对象中的某些内容,它会在两端反映出来。

var cacheArray = [{ item: 1 }, { item: 2}];  
table[0][0] = cacheArray[0];  
console.log(table[0][0].item);  // 1 
cacheArray[0].item = 9;  
console.log(table[0][0].item);  // 9.  

请注意,数组和表格没有改变。它们仍然指向相同的对象。

于 2015-09-27T14:20:05.033 回答