Search code examples
javascriptangularjsng-optionsangular-ngmodel

How to add more than one select element with same set of ng-options


This question may be very trivial but its driving me nuts. I can have n number of elements on my page that are added dynamically. All these will have the same set of options for them.

<select class="form-control action"
      data-ng-options="action.name for action in statementData" 
      data-ng-model="selectedRules.statementOptions"
> 

This is the mark-up for one of such elements.

Problem: When I change or select something in one select element, all the others are updated. I dont want that. This might be happening coz of the same model object. But if i remove model then there is no data.


Solution

  • If you simply copy the variable, its passed by reference and change to one will change the other.

    Try creating two variables using angular.copy() and use it for two select options.

    Try something like below :

    <!-- First select -->
    <select class="form-control action"
      data-ng-options="action.name for action in statementData" 
      data-ng-model="selectedRules.statementOptions">
    
    <!-- Second select -->
    <select class="form-control action"
      data-ng-options="action.name for action in statementData1" 
      data-ng-model="selectedRules.statementOptions"> 
    

    In Controller you will have to do.

    $scope.statementData1 = angular.copy(statementData);
    

    By using angular.copy() separate copies are made for both variables in $scope.