climboid
climboid

Reputation: 6962

Multiple select boxes with different selected values in angularJS

I have multiple select boxes and I'm using angular JS. Each select box needs to have a different selected value. So far everything I've seen has elements that share the same selected value. In order to achieve this a scope is used. Since I can potentially have hundreds of drop downs... actually thousands... what is the correct approach here? Create a scope for each one? Try to have one scope that mutates with each select box?

Here is an example with what I have jsfiddle.

Any help is much appreciated.
Thanks


function MyCntrl($scope) {
$scope.colors = [
    {name:'black'},
    {name:'red'},
    {yellow:'yellow'}
]
$scope.isSel = $scope.colors[1];
}

Upvotes: 2

Views: 5002

Answers (2)

Benny Bottema
Benny Bottema

Reputation: 11513

You need to bind each select box to its own scope. You can do it manually, binding each one to a new object instead of the same isSel, or you can use a ng-repeat like so:

http://jsfiddle.net/zmU8R/9/

html:

<div ng-app="">
  <div ng-controller="MyCntrl">
      <div ng-repeat="control in controls">
          <select ng-model="control.isSel" ng-options="c.name for c in colors"></select><br />
      </div>
      <hr />
      <div ng-repeat="control in controls">
          {{control.id}}: {{control.isSel}}
      </div>
  </div>
</div>

script:

function MyCntrl($scope) {
    $scope.controls = [
        {id: 1, isSel:null},
        {id: 2, isSel:null},
        {id: 3, isSel:null}
    ];
    $scope.colors = [
        {name:'black'},
        {name:'red'},
        {name:'yellow'}
    ];
}

Upvotes: 2

Pythonic
Pythonic

Reputation: 486

Not sure I've figured out what you exactly want. As far as I understand, you need each selectbox to have different value. So, you need to bind each selectbox to a different variable.

<div ng-app="myApp">
  <div ng-controller="myCtrl">
    <hr/>
    <div ng-repeat="n in [] | range: selectionsCount">
        <select ng-model="selectedValues[$index]" ng-options="c.name for c in colors"></select>
    </div>
    {{ selectedValues }}
  </div>
</div>

For a much clearer example, I made selectboxes count variable here.

angular.module('myApp', [])
    .controller('myCtrl', function ($scope) {
        $scope.colors = [
            {name: 'black'},
            {name: 'red'},
            {name: 'yellow'}
        ];
        $scope.selectedValues = [];
        $scope.selectionsCount = 5;
    })
    .filter('range', function () {
        return function(input, total) {
            total = parseInt(total);
            for (var i=0; i<total; i++)
                input.push(i);
            return input;
        };
    });

You can test it here: http://jsfiddle.net/zmU8R/7/ If I misunderstood your question, feel free to correct me.

Upvotes: 2

Related Questions