使用网址

时间:2016-04-22 03:49:22

标签: javascript html angularjs user-interface angularjs-ng-change

我遇到了一个非常棘手的问题。我的Angular UI为用户提供了3个下拉菜单,第3个菜单基于前两个菜单是动态的。这很好用。我还有一个动态URL,映射到3个下拉菜单,以便浏览器可以自动填充它们。例如,如果浏览器网址为" / home?selectedLetter = A& selectedNumber = 2& selectedColor = 7891",则在我将此网址粘贴到新标签页后,下拉列表应自动设置为A, 2,和黑色(对应阵列中的7891)。

但是,只有selectedLetter和selectedColor下拉列表按预期填充,selectedColor为空(调试后我发现它是因为从不调用setColorSelection()。前两个菜单中的ng-change()调用永远不会被触发)。浏览器肯定知道selectedColor是7891,但只是没有在UI中显示它。即使我可以让它显示,我如何将其转换为" Black"在菜单中?我似乎无法解决这个问题。有什么想法吗?

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];
    }
}

1 个答案:

答案 0 :(得分:0)

只有在更改选择框的值时才会触发

ng-change。所以,尝试使用:

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

在设置模型之前,colorSelection已准备就绪。