我正嘗試使用AngularJS提供可切換的下拉列表,其中各種選項的選擇將觸發不同的列表。 ng-switch
似乎是正確的做法,但我的ng-model
在ng-switch
內部沒有約束力。綁定工作正常,如果我不使用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>"
}
});
我明白了!謝謝!你知道我有沒有辦法重新編譯'template'?我有一些自定義模板代碼,只要切換到另一個下拉列表,就不會編譯。 –
您可以使用不同的角度html模板重新編譯html(請參閱[這些文檔](http://docs.angularjs.org/api/ng.$compile)),但它可能是你想要做的事情的矯枉過正。看看原始示例的[修改後的版本](http://jsfiddle.net/LUzXT/5/),而不用創建指令,以防您繞過自定義指令。如果你創建一個小提琴的例子,我(或其他人)可以嘗試和幫助。 – Gloopy
我無法創建小提琴,因爲我正在使用第三方庫。實質上,我使用[bootstrap-select](http://silviomoreto.github.io/bootstrap-select/),它使用css和js來設置下拉列表的樣式。但是一旦我切換列表,樣式就消失了。 –