gpt4 book ai didi

javascript - AngularJS 在模型更新期间丢失了 css 类(DOM 重绘)

转载 作者:行者123 更新时间:2023-11-30 18:09:34 26 4
gpt4 key购买 nike

我有一个表,其行循环通过一些模型数据。单击表格单元格时,该行的所有单元格都会切换 .active(背景变为红色)。这工作正常(尽管我最终会添加一个更复杂的检查器,从该行的所有兄弟中删除 .active )。但是,我的表正在通过更新模型并导致重新绘制表的 WebSocket 推送/消息接收数据。发生这种情况时,我的“选择”就丢失了。

<tr ng-repeat="item in items | orderBy:'time':true">
<td
ng-click="items[$index].active =! items[$index].active"
ui-refresh="items[$index].active"
ui-jq="toggleClass"
ui-options="'active'"
>{{item.time | date:'hh:mm a'}}</td>
<td
ng-click="items[$index].active =! items[$index].active"
ui-refresh="items[$index].active"
ui-jq="toggleClass"
ui-options="'active'"
>
<a href="#/items/details/{{item.id}}">{{item.name}}</a>
</td>
</tr>

在我的 Controller 中,新的 WebSocket 消息被推送到我的数组 items:

function Items($scope , WebSocket)
{
$scope.items = [];

WebSocket.on('items', function(data)
{// receive a bunch of items onload
$scope.items = data.items;
});

WebSocket.on('item', function(data)
{// receive subsequent items as they are pushed
$scope.items.push(data.item);
});
}

所以我想知道为什么 items[$index].active 不会通过 DOM 重绘持续存在(并保留其 active css 类)。此外,如果有人对我如何保持我的“状态”有解决方案,那就太好了。

通常我完全松开 css 类,但有时(看似随机)它会重新出现在与原始行相同的表格位置(比如第二行)的新行上,即使原始行已移动向下(到第 5 行)并且当添加 active 时,出现 active 的新行不存在。

我会发布一个示例,但 Plunkr 和 jsfiddle 都不支持 NodeJS(它推出 WebSocket 消息)并且是演示行为所必需的。

解决方案

基于 Alex's answer ,我稍微修改了我的 Controller 以添加第二个数组:

function Items($scope , WebSocket)
{
$scope.items = [];
$scope.rowSelection = [];// <- THIS IS NEW

WebSocket.on('items', function(data)
{// receive a bunch of items onload
$scope.items = data.items;
});

WebSocket.on('item', function(data)
{// receive subsequent items as they are pushed
$scope.items.push(data.item);
});
}

在我的模板中,将 items[$index].active 换成 rowSelection[$index](因为第二个数组的唯一目的是记住谁是选择/事件,它不需要 active 属性)。

最佳答案

您正在丢失 items[$index].active 中的值,因为当 WebSocket 更新时整个 items 数组被覆盖。

要保持选中状态,您应该将其存储在不受影响的单独变量中。

类似于:

在 Controller 中

$scope.items = [];
$scope.itemStatus = [];

在指令/模板中

  <td
ng-click="itemStatus[item.id].active =! itemStatus[item.id].active"
ui-refresh="itemStatus[item.id].active"

关于javascript - AngularJS 在模型更新期间丢失了 css 类(DOM 重绘),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14948389/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com