2013-09-23 42 views
1

在我的場景中,我有一個選擇下拉列表併爲其指定了ng模型。下拉菜單中的每個項目都對應於多個複選框,這些複選框在進行選擇時會被選中。難點在於我不能只檢查一個簡單的鍵:值,因爲複選框並不是特定於任何特定的選擇。例如:根據AngularJS中的多個條件更改複選框狀態

<select> 
    <option>Dog</option> 
    <option>Cat</option> 
    <option>Bird</option> 
</select> 

<input type="checkbox">Is an animal 
<input type="checkbox">Can bark 
<input type="checkbox">Can meow 
<input type="checkbox">Can tweet 
<input type="checkbox">Has four legs 
<input type="checkbox">Has wings 

所以,你可以,「是一種動物」和「有四條腿」的複選框不是唯一的。我目前的實現使用一個簡單的條件表達式來評估複選框是否被標記(ng-checked =「animal =='dog'」),但當然這排除了其他兩種可能性。所以我想知道是否有一個原生的Angular方法來處理OR語句或數組。或者,如果沒有,我怎麼能用JavaScript或jQuery去解決這個問題?

回答

4

看到這個小提琴:http://jsfiddle.net/QHza7/

模板:

<div ng-app ng-controller="Test"> 
    <select ng-model="opts" ng-options="a.opts as a.name for a in answers"></select> 
    <br/> 
    <input type="checkbox" ng-model="opts.animal" />Is an animal<br/> 
    <input type="checkbox" ng-model="opts.bark" />Can bark<br/> 
    <input type="checkbox" ng-model="opts.meow" />Can meow<br/> 
    <input type="checkbox" ng-model="opts.tweet" />Can tweet<br/> 
    <input type="checkbox" ng-model="opts.legs4" />Has four legs<br/> 
    <input type="checkbox" ng-model="opts.wings" />Has wings<br/> 
</div> 

代碼:

function Test($scope) { 
    $scope.answers = [ 
     {name:"Dog", opts:{animal:true,bark:true,legs4:true}}, 
     {name:"Cat", opts:{animal:true,meow:true,legs4:true}}, 
     {name:"Bird", opts:{animal:true,tweet:true,wings:true}} 
    ]; 
    $scope.opts = null; 
} 
+0

啊太棒了!這種簡單的解決方案。非常感謝。 – iamsar