本文介绍了AngularJs ng-repeat跟踪通过$ index问题与angular-bootstrap-switch的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

AngularJs ng-repeat angular-bootstrap-switch

我正在使用:

ng-repeat="item in items track by $index"

当我通过以下方式将新项添加到数组的第一个索引中时:

When I added a new item into the first index of array by:

newItem = {};    
items.splice(0, 0, newItem);

DOM包含一个bs-switch:当添加新项目时,它会根据$ index重用数组中的第一个元素,因此它不会重新呈现(这就是我从此文档中获得的).我遇到的问题是上一个元素具有开机.

The DOM contain a bs-switch:When a new item added it reuse the first element in array base on $index, so it doesn't re-render (that's what I get from this docs). The problem I have is the previous element has switch-on.

我遇到的DOM效果问题是类"打开"不会在新项目上刷新,并且会一直存在.

The DOM effect issue I have is the class "switch-on" doesn't refresh on new item and it keep on.

预期:在这种情况下,我要关闭,而不是像图像一样打开.因为它是一个空对象

Expected: In this case I want to switch is off instead of on like the image. Cause it's an empty object

P/s:业务原因

  • 我无法为该 Switch 添加默认值.它必须是一个空对象

  • I cannot add default value for that Switch. It need to be an empty object

我也不能使用item对象的任何标识符来跟踪替换为$ index

I also cannot use any identifier of the item object to track replace to $index

如果我使用$ id使用默认轨道,也会引起一些业务问题

If I use default track by $id it will cause some business issue also

在Angular 1.5或更高版本上工作的TEMP解决方案:

使用angular 1.5,您可以使用 angular-bootstrap-switch 0.5 .1

With angular 1.5 and you can use angular-bootstrap-switch 0.5.1

在frapontillo发布更改后,它将解决此问题:"在模型更改时进行开关更改"触发"

It will fixed the issue, after frapontillo release a changed: "Make "switch-change" trigger when model changes"

非常感谢您的支持.

推荐答案

我从您的问题中看到的是您想向主数组添加一个新项,并且当它呈现时,您希望将其切换为 off 默认.

What I perceive from your question is that you want to add a new item to main array and when It renders, you want it's switch to be off by default.

您需要牢记一些事情.

  1. ng-repeat在我们的DOM中仅表现为循环.

  1. ng-repeat only behaves as a loop in our DOM.

如果要默认关闭电源,则必须在主阵列的每个项目中都有一个模型.它将跟踪DOM中每个开关的状态.

If you want to have the switch off by default, you must need to have a model for that in every item of the main array. It'll keep track of every switch's state in DOM.

这是您应该尝试的

从您的控制器:

newItem = {switchState: 0};    
items.splice(0, 0, newItem);

通过您的HTML:

<div ng-repeat="item in items track by $index">
<!-- your Name and Decription input fields.. -->

<input
    bs-switch
    ng-model="item.switchState" />

所以我认为您忽略了导致问题的angular-bootstrap-switch的ng-model.

So I think you're ignoring ng-model of angular-bootstrap-switch which causes you the problem.

这篇关于AngularJs ng-repeat跟踪通过$ index问题与angular-bootstrap-switch的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

10-27 07:17