angularjsangular-chosen

Make option selected by default using chosen and angularJS


Im not sure why is it that the option is not selected by default, the values are hard coded and I explicitly added 'selected' attribute on option tag but its not working. I also tried selected="selected" but still its not working.

in View:

<div class="controls">
            <select chosen="" data-ng-model="assignments"  multiple="" 
                    class="span chzn-select" style="width: 150px">
                <option value="Police">Police</option>
                <option selected value="Reporter">Reporter</option>
                <option value="Developer">Developer</option>
            </select>
        </div>

Solution

  • This would work if you didn't have the multiple attribute. In order to get this wto work with a multuple select, you need to set it up using ng-options and then store an array of what should be selected. See this fiddle:https://jsfiddle.net/btqLg76v/1/

    JS:

    var app = angular.module('MyApp', []);
    
    app.controller('MyController', function($scope) {
      $scope.selectOptions = ['Police','Reporter','Developer'];
      $scope.assignments = [$scope.selectOptions[0],$scope.selectOptions[2]];
      console.log($scope.assignments);
    });
    

    HTML:

    <body ng-app="MyApp">
      <div ng-controller="MyController">
        <select ng-model="assignments" ng-options="selectOptions for selectOptions in selectOptions" multiple>
        </select>
      </div>
    </body>