AngularJS select選擇框初始化問題
阿新 • • 發佈:2019-02-09
Angularjs select初始化問題
問題描述:
angularjs 中的select往往會遇到選擇框沒有初始化的問題,表現形式就是一開始為空,但是選擇後空白就消失。十分難看。
解決方案:
比如說如下的select:
<select ng-model="step.dataSource" ng-options="item.codeValue for item in dataSources"></select>
如果不初始化的話就會遇到如上所述的問題。
我推薦這麼解決:
step.dataSource = dataSources[0];
這樣ng-model就有一個初始化的值,不會有空格。有時候遇到需要更加複雜的顯示效果時,這種解決方式可能滿足不了。但是我嘗試過ng-repeat+ng-selected,效果並不好,所以建議使用如上的方式,遇到需要複雜的選項的時候再封裝一層,比如:
//用於解決Select標籤初始化問題的封裝 scope.perPageList = []; scope.perPageSelect = null; /** * 將真實資料重新整理入封裝 */ var refreshPerPageList = function () { scope.perPageList = []; for (var i = 0;i < conf.perPageOptions.length;i ++){ var tempPerPageItem = {}; tempPerPageItem.value = conf.perPageOptions[i]; tempPerPageItem.view = tempPerPageItem.value + "條/頁"; scope.perPageList.push(tempPerPageItem); if (conf.perPageOptions[i] == conf.itemsPerPage){ scope.perPageSelect = scope.perPageList[i]; } } //console.log(scope.perPageList); //console.log(scope.perPageSelect); }
在頁面中這麼寫<select ng-model="perPageSelect" ng-options="option.view for option in perPageList " ng-change="changeItemsPerPage()"></select>