1

My ng-selected expression sets selected="selected" html attribute in <option> tag ( you can see it in screenshot http://prntscr.com/bmgozg ) but for some unknown to me reason this <option> element is still not selected on web page...

I use Angular 1.4.7.

<select ng-model="link.destination_slide_number">
                        <option value="{{$index + 1}}"
                                ng-repeat="canvas in vm.canvases"
                                ng-selected="link.destination_slide_number == $index + 1">Go to slide #{{$index + 1}}
                        </option>
</select>
yaru
  • 1,260
  • 1
  • 13
  • 29
  • Refer http://stackoverflow.com/questions/18194255/how-to-have-a-default-option-in-select-box-angular-js – Ajay Jun 29 '16 at 07:33

2 Answers2

1

You can (will) run into some strange issues if you repeat over option elements in a select. Angular implemented a directive ng-options to help you with that: https://docs.angularjs.org/api/ng/directive/ngOptions

Per Hornshøj-Schierbeck
  • 15,097
  • 21
  • 80
  • 101
0

Thanks Per Hornshøj-Schierbeck, I was able to achieve a success with this code:

html

<select ng-model="link.destination_slide_number"
        ng-options="idx * 1 + 1 as vm.formatText(idx) for (idx, choice) in vm.canvases">                        
</select>

js

function formatText(canvasIdx) {            
            return 'Go to slide #' + (Number(canvasIdx) + 1);
        }
yaru
  • 1,260
  • 1
  • 13
  • 29
  • Just a note. Seeing that you're not really using canvases for anything but a loop counter, why not create an object that holds the correct data and bind to that instead of vm.canvases? That will get rid of the formatText and wierd idx syntax in the view. – Per Hornshøj-Schierbeck Jun 29 '16 at 08:42
  • I need to create as many – yaru Jun 29 '16 at 08:48
  • 1
    i would still, in the controller do something like var model = vm.canvases.map(function (c) { return {...} }); That way, the controller does the formatting and logic and the view (html) is none the wiser. – Per Hornshøj-Schierbeck Jun 29 '16 at 10:38