问题
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: 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.
回答1:
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.
ng-repeat
only behaves as a loop in our 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.
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.
来源:https://stackoverflow.com/questions/51320091/angularjs-ng-repeat-track-by-index-issue-with-angular-bootstrap-switch