Home ng-repeat with ng-selected
Reply: 2

ng-repeat with ng-selected

Carmageddon
1#
Carmageddon Published in 2017-11-14 20:57:15Z

I am trying to figure out how to generate list of option elements using ng-repeat, but one of them to be marked as the selected option on load.

After googling, what I found is this base, which I modified by adding the selected property to the data objects https://plnkr.co/edit/7g4MeAQnG4PzpnrebBGc?p=preview However, it seems that ng-selected="option.selected == true" has no effect :(

Why? I also have the more complex example here: http://jsfiddle.net/ej5fx3kr/14/ which works, although I am not sure what is the difference, or what is the model here used for (note: changing the model name from "program" to anything, it still works... so not sure what is the purpose).

Bonus points: How do I debug code in AngularJS in directives? Like experiment in debug mode line by line to actually see what are the variable values in that particular scope, what is available to use, etc...

My ultimate goal in this question, is to load list of values via ajax on page load in the controller, IF there is a routeParam in the URL, find it in the list of loaded values, and add selected attribute, then set selected=true in the generated HTML on page load, otherwise not pre-select anything in the populated select box on the page load, so this is why its important for me to understand this on the simplest example before trying to plug this in.

Thanks!

Claies
2#
Claies Reply to 2017-11-14 21:28:58Z

The "Angular Way" to handle this is to use ng-options instead of ng-repeat, and then simply set the model equal to the default value on controller load.

For example:

<select ng-options="option.name for option in data.availableOptions" 
        ng-model="selectedItem"></select>

$scope.selectedItem=$scope.data.availableOptions[2];

For a more advanced case, where your ng-model might not be the object in the array, but a single property, you can use a modified version of ng-options:

<select ng-options="option.id as option.name for option in data.availableOptions" 
        ng-model="selectedId"></select>

$scope.selectedId = '2';

Here is a modified version of your plunker showing these different possibilities: https://plnkr.co/edit/xzYmXf8C3WuZaelwj5hO?p=preview

jenil christo
3#
jenil christo Reply to 2017-11-14 21:08:46Z

Using ng-selected = true inside ng-repeat would solve this . However be sure of the data that you call in ng-repeat.For additional debugging and experiment line by line use chrome debugger .go to source tab and set break points on the js lines that you need to debug.This will let you debug line by line by pause and play . Hope this helps.Thanks

You need to login account before you can post.

About| Privacy statement| Terms of Service| Advertising| Contact us| Help| Sitemap|
Processed in 0.323271 second(s) , Gzip On .

© 2016 Powered by mzan.com design MATCHINFO