0

Currently I'm trying to figure out a way to preselect a drop down option depending on parameters in the URL. IE: www.example.com/#/Two, if you were to hit that URL I would like to have Two in the 'items' scope preselected to the 'selectedItem' scope. Right now with the below code all it does it default to 'One' in the 'items' scope. I've tried parsing the URL and injecting it into the 'selectedItem' scope but that didn't work either.

<select ng-model="selectedItem" 
        ng-options="item as item.name for item in items">
</select>

var testURL = 'http://www.example.com/#/Two';

$scope.items = [
  {name:'One', value:'check1'},
  {name:'Two', value:'check2'}
];

$scope.selectedItem = $scope.items[1];

Fiddle for convenience: Sandbox

Starboy
  • 1,635
  • 3
  • 19
  • 27
  • I wonder if this is what you need: http://stackoverflow.com/questions/979975/how-to-get-the-value-from-url-parameter – Topological Sort Nov 12 '14 at 21:13
  • @WillBriggs I actually tried doing that but since it goes back to a string, and not an object (What I think Angular is expecting), causes it to fail : ( – Starboy Nov 12 '14 at 21:17
  • @WillBriggs Here's even an example with the selected option hardcoded, which again doesn't seem to work http://jsfiddle.net/MTfRD/1409/ – Starboy Nov 12 '14 at 21:20

1 Answers1

0

I usually use a $timeout method to make sure the timing it correct and then loop through the items and find the correct one. Something like:

$timeout(function () {
    var page = testURL.substr(testURL.length - 3);
    for (var i = 0; i < $scope.items.length; i++) {
        if ($scope.items[i].name === page) {
            $scope.selectedItem = $scope.items[i];
        }
    }
});

Updated fiddle.

Bryant
  • 8,660
  • 1
  • 33
  • 53