jebmarcus jebmarcus - 7 months ago 8
HTML Question

Populating dropdown menus with URL

I have ran into a really tricky problem. My Angular UI gives users 3 dropdown menus and 3rd menu is dynamic based on the previous two menus. This works fine. I also have a dynamic URL that maps to the 3 dropdowns menus so the browser can populate them automatically. For example, if the browser URL is "/home?selectedLetter=A&selectedNumber=2&selectedColor=7891", then after I paste this URL in a new tab, the dropdowns should automatically be set to A, 2, and Black (which corresponds to 7891 in the array).

However, only the selectedLetter and selectedColor dropdowns populate as expected, selectedColor is empty (after debugging I found it's because setColorSelection() is never called. ng-change() calls in the first two menus are never triggered). The browser definitely knows that selectedColor is 7891, but just doesn't show it in the UI. Even if I can get it to show, how do I convert it to "Black" in the menu? I just cannot seem to get around this problem. Any ideas?

HTML:

<select ng-model="selectedLetter"
ng-change="setColorSelection()"
ng-options="letter as letter for letter in letters">
</select>
<select ng-model="selectedNumber"
ng-change="setColorSelection()"
ng-options="number as number for number in numbers">
</select>
<select ng-model="selectedColor"
ng-options="color.ID as color.colorName for color in colorSelection">
</select>


Angular inside controller:

$scope.letters = ['A', 'B'];
$scope.numbers = ['1', '2'];

var colors = { // Note that all IDs are unique
'A1': [{"colorName": "Red", "ID": "1001"}, {"colorName": "Pink", "ID": "3002"}],
'A2': [{"colorName": "Blue", "ID": "9022"}, {"colorName": "Black", "ID": "7891"}],
'B1': [{"colorName": "Yellow", "ID": "5436"}, {"colorName": "Orange", "ID": "4444"}]
};

$scope.colorSelection = [];


// This populates selectedLetter and selectedNumber, doesn't work for selectedColor
var params = $location.search()
if (params.selectedLetter) {
$scope.selectedLetter = params.selectedLetter;
}
if (params.selectedNumber) {
$scope.selectedNumber = params.selectedNumber;
}
if (params.selectedColor) {
$scope.selectedColor = params.selectedColor;
}


$scope.setColorSelection = function() {
if ($scope.selectedLetter && $scope.selectedNumber) {
$scope.colorSelection = colors[$scope.selectedLetter + $scope.selectedNumber];
}
}

Answer

ng-change gets triggered only when the value of the select box is changed. So, try using:

if (params.selectedColor) {
    if ($scope.selectedLetter && $scope.selectedNumber) {
        $scope.colorSelection = colors[$scope.selectedLetter + $scope.selectedNumber];
    }
    $scope.selectedColor = params.selectedColor;
}
Comments