Hossam Elsagheer Hossam Elsagheer - 8 months ago 56
AngularJS Question

Angular ng-model ng-selected

I want to bind a model value to selected item

<select id="hours" ng-model="v.T_Hour">
<option ng-repeat="n in [].constructor(24) track by $index" ng-selected="{{$index==v.T_Hour}}" value="{{$index}}">{{$index>9?$index:"0"+$index}}:00</option>

I want after the page loads , the value of the model 'v.T_Hour' to be selected in select , i assign the value of the model in the controller, when i view the resulting HTML i see that the value is selected in the HTML code ,but not selected in the select control , and the select control displays an empty item.

Answer Source

Try this

    ng-options="option.name for option in v.data track by option.value" 
    class="form-control inline-forms">
    <option value="" selected>{{placeHolder}}</option>

and in controller

$scope.v = {data:[], selected:{}, placeHolder:""}
$scope.v.data = [{name:"nameOne", value:"valueOne"},{name:"nameTwo", value:"valueTwo"},{name:"nameThree", value:"valueThree"}]
$scope.v.selected = $scope.v.data[0]
$scope.v.placeHolder = "Click to Select"

According Angular documentation ngOption is better way to go than ngRepeat: Choosing between ngRepeat and ngOptions In many cases, ngRepeat can be used on elements instead of ngOptions to achieve a similar result. However, ngOptions provides some benefits:

more flexibility in how the 's model is assigned via the select as part of the comprehension expression reduced memory consumption by not creating a new scope for each repeated instance increased render speed by creating the options in a documentFragment instead of individually Specifically, select with repeated options slows down significantly starting at 2000 options in Chrome and Internet Explorer / Edge. see: https://docs.angularjs.org/api/ng/directive/select