1

I am having an issue with AngularJs ng-repeat and angular-bootstrap-switch

I am using:

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);

The DOM contain a bs-switch: enter image description here 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.

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: Cause of the business so

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

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

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

TEMP SOLUTION FOR WHO WORKING ON Angular 1.5 or Upper:

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

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

Thank you so much for supporting.

Le Dac Sy
  • 381
  • 3
  • 16
  • The temp solution should be an answer, not an edit to the question and should be on the original question, not the duplicate – Danny Varod Jul 16 '18 at 08:14

1 Answers1

0

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.

Well there are couple of things you need to keep in mind.

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

  2. 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.

Here's what you should try

From your controller:

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

From your HTML:

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

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

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

Zain Mohsin
  • 97
  • 1
  • 11
  • Thank you for your fast response. But cause I cannot set default value for that item, I have mentions before: "I cannot add default value for that Switch. It need to be an empty object". So ng-model doesn't help this time. I think. – Le Dac Sy Jul 13 '18 at 08:33