0

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>
XDProgrammer
  • 853
  • 2
  • 14
  • 31

1 Answers1

1

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>
Ronnie
  • 11,138
  • 21
  • 78
  • 140
  • *"you need to set it up using ng-options"*. Well, I have to go ahead and say: of course it's always good to use `ngOptions` directive, however he can do that way also if he wants. – developer033 Aug 06 '16 at 00:23
  • Hi thanks for the code, I think its really close, was able to use it in my first implementation. But how about if it involves asynchronous operation like requesting from an api using `http.get` and in `then` i will set the selected options `$scope.assignments = //whatever the request returns`. – XDProgrammer Aug 06 '16 at 06:58