0

I have an Angular ui-select that is used to toggle some checkboxes (generated with ng-repeat) based on the selected option.

The checkboxes can also manually be toggled as well, and that's where things seem to go wrong.

Scenario is as follows:

  1. Select an option. Some checkboxes are toggled based on the ingredients property of the specified option on the $scope.recipes.available model.
  2. Manually toggle an additional checkbox.
  3. Select a different option on the select. The corresponding checkboxes are correctly toggled.
  4. Switch back to the first selected option. Instead of only toggling the checkboxes originally specified on the ingredients property, the manually modified checkbox is also toggled. While debugging I see that somehow the ingredients property has been modified.

This plunkr demonstrates the problem.

So far, after reading countless scoping issues (I'm new to Angular) and trying again and again to refactor my code I haven't been able to fix this problem.

Before going ahead and trying to refactor the code one more time, I'd like to understand what's going on in here.

Why is the ingredients property being modified?

excentris
  • 471
  • 1
  • 7
  • 25

1 Answers1

0

Your bundles array is being updated in your toggleBundleSelection function. There is nothing that resets the array when the recipe selection changes. Since bundles is on $scope the values are retained for the life of the controller instance.

jbrown
  • 3,025
  • 1
  • 15
  • 22
  • When the recipe changes I do `$scope.bundles.selected = $scope.recipes.available[$selectedRecipe].ingredients;`. Shouldn't that reset `$scope.bundles.selected`? – excentris Nov 24 '15 at 13:22
  • Ah, missed that. You be shouldn't assigning the one array to the other. You will want to want to set it equal to a copy like this: $scope.bundles.selected = angular.copy($scope.recipes.available[$selectedRecipe].ingredients); – jbrown Nov 24 '15 at 13:30
  • That indeed works (thanks!), but I still do not understand why is it necessary. I am assigning the content of ingredients to `$scope.bundles.selected` and not the other way around... – excentris Nov 24 '15 at 13:36
  • 1
    Using the assignment operator, you are actually just referencing the original array. Arrays are reference types. That means, that they don't actually store values, they only store references to those values.What you where doing is copying a reference to a memory location, meaning that any changes to the memory at that location (including removing elements) will be reflected in both arrays. – jbrown Nov 24 '15 at 13:40
  • Well that makes sense. Thank you very much for your explanation! – excentris Nov 24 '15 at 13:43