2013-11-28 37 views
1

我正在研究一對內容相互關聯的組合。如何擺脫依賴選擇的默認值?

HTML

<span>{{lblRegion}}</span> 
    <select ng-model="currentRegion" 
      ng-options="region.name for region in regions" 
      ng-change="checkAll()"> 
    </select> 


    <span>{{lblCountry}}</span> 
    <select ng-model="currentCountry" 
      ng-options="country.name for country in currentRegion.countries" 
      ng-disabled="currentRegion.id===0"> 
    </select> 

JS

$scope.regions = regions; 
    $scope.currentRegion = regions[0]; 
    $scope.currentCountry = $scope.currentRegion.countries[0]; 

    $scope.checkAll = function() { 

    if (currentRegion.id !== 0) { 
     $scope.test = true; 
    } else { 
     $scope.test = false; 
    } 
    } 

var regions = [{ 
    'id': 0, 
    'name': 'All', 
    'countries': [{ 
     'id': '0', 
     'name': 'All' 

    }] 
    }, 
    ... 

行爲必須滿足這樣的:

  1. 兩個功放音箱的 '全部' 選項。
  2. 「區域」組合的內容設置「國家」組合的可能值。
  3. 如果區域組合設置爲「全部」,則國家/地區組合會被禁用,其內容爲「全部」選項。

我想擺脫總是出現在國家組合上的空白默認選項。我讀過ng-init可以完成這項工作,但ng-init docs指出不應該以這種方式管理這個問題。

我怎樣才能刪除空的選項?

回答

1

默認漸漸選擇空白值,因爲第二ng-option取決於currentCountry.countries,改變,和currentRegion值,這是regions[0].countries[0],不在此列表中。只要currentRegion更改,即可通過將currentRegion的值設置爲currentRegion.countries[0]來更正此錯誤。

這可以在ng-change中完成,就像您嘗試過的那樣。

但是,我不信任訂購ng-changeng-model。因此,我寧願爲任務設置手錶:http://plnkr.co/edit/TnHC039Hg7x0Oj9DmEkk?p=preview

控制器

$scope.$watch('currentRegion', function (newVal) { 
    if (typeof newVal !== 'undefined') { 
    $scope.currentCountry = newVal.countries[0]; 
    } 
}) 

模板

<!-- Without ng-change --> 
    <select ng-model="currentRegion" ng-options="region.name for region in regions"></select> 
+0

我喜歡你的答案......但我想知道是否有機會逃避使用$ watch ... – JPCF

+0

@JPCF你總是可以使用'ng-change =「currentCountry = currentRegion.countries [0]「,儘管它會隱藏模板中的一些邏輯。 –

+0

是的......這是另一種選擇......我希望它完全是聲明性的......但是,'根據我們與@Maxim Shoustin的討論,如果它尋找老鼠'貓的顏色並不重要' – JPCF

1

寫深$watch

$scope.$watch(function() { 
    return $scope.currentRegion; 
}, 
function (newValue, oldValue) { 
    $scope.currentCountry = newValue.countries[0].name; 
}, true); 

演示Plunker

+0

你的代碼有一個奇怪的行爲。假設以下序列:1.選擇一個區域,2.選擇一個國家,3.在區域組合中選擇「全部」。此操作的結果是將國家/地區組合設置爲阻止值「」。我正在研究... – JPCF

+0

ng-init =「currentCountry = currentRegion.countries [0] .name」將模型的值設置爲索引0處國家名稱的預期值? e.gr.如你所說,查詢currentCountry的id將在設置ng-init之後返回currentRegion.countries [0]的id值。 – JPCF

+1

對不起,我改變了我的答案,我想沒有辦法,只能用'watch'。因爲'ng-init'只啓動一次。補充Plunker –

1

最快的方式擺脫毛坯只需將以下內容添加到您的checkAll()函數中:

$scope.currentCountry = $scope.currentRegion.countries[0]; 

這樣的:

$scope.checkAll = function() { 
    $scope.currentCountry = $scope.currentRegion.countries[0]; 
    if (currentRegion.id !== 0) { 
     $scope.test = true; 
    } else { 
     $scope.test = false; 
    } 
    } 

如果不設置一個選擇框的值,它會自動添加一個空白的第一項。所以爲了避免這種情況,顯然要給它一個價值。