我正在尝试使用AngularJS来提供一个可切换的下拉列表,其中各种选项的选择将触发不同的列表。 ng-switch
似乎是正确的方法,但我ng-model
在ng-switch
内没有约束力。如果我不使用ng-switch
,绑定工作正常,但如果是这种情况我不知道如何切换我的下拉列表。这可能是什么问题?
jsFiddle:http://jsfiddle.net/tanweihao88/LUzXT/3/
HTML:
<select ng-model="periodRangeModel" ng-options="item for item in items"></select>
<div ng-switch on="periodRangeModel">
<span ng-switch-when="Month"><period-selector items="monthOptions" ng-model="periodModel"></period-selector></span>
<span ng-switch-when="Quarter"><period-selector items="quarterOptions" ng-model="periodModel"></period-selector></span>
<br>
</div>
JS:
angular.module('myApp', [])
.controller("MyCtrl", function($scope) {
$scope.items = ['Month', 'Quarter'];
$scope.periodRangeModel = "Month";
$scope.quarterOptions = ["Jan-Mar", "Apr-Jun", "Jul-Sept", "Oct-Dec"];
$scope.monthOptions = ["January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December"];
$scope.periodModel = $scope.monthOptions[0];
})
.directive('periodSelector', function() {
return {
restrict: 'E',
replace: true,
scope: { items: '=', ngModel: '='},
template: "<span><select ng-options='period for period in items' ng-model='ngModel'></select></span>"
}
});
答案 0 :(得分:6)
绑定不能按预期工作的主要原因是ng-switch
创建了一个新范围,当绑定到字符串原语时,原始periodModel
没有按预期更新(因为新范围是periodModel
正在更新中。
This question详细了解了幕后发生的事情,您可以查看Angular Batarang Chrome Extension,直观地看到各种范围。
您可以通过绑定到this updated fiddle中的对象值来绕过它。主要变化是:
1)将periodModel
更改为对象并设置属性(在此示例中称为value
)
$scope.periodModel = {
value: $scope.monthOptions[0]
};
2)更改任何绑定代码以访问periodModel.value
而不是periodModel
<period-selector items="monthOptions" ng-model="periodModel.value"></period-selector>
Model: {{periodModel.value}} (this is supposed to change)