2015-04-05 50 views
3

我有一組材料設計複選框,我想將它們的值綁定到控制器中的數組。將角度材質設計複選框綁定到控制器中的陣列

爲了實現這一點,我使用了this SO answer中描述的第一種方法。雖然值正在被添加並從列表中刪除,但當我點擊它們時,這些框不再顯示爲「已檢查」。我的代碼在下面,我也在this codepen中重新創建了這個問題。

HTML我複選框

<md-checkbox 
    ng-repeat="site in websites" 
    value="{{site}}" 
    ng-checked="selection.indexOf(site) > -1" 
    ng-click="toggleSelection(site)"> 
    {{site}} 
</md-checkbox> 

的JavaScript控制器

$scope.websites = ['Facebook', 'Twitter', 'Amazon']; 
    $scope.selection = ['Facebook']; 
    $scope.toggleSelection = function toggleSelection(site) { 
    var idx = $scope.selection.indexOf(site); 

    // is currently selected 
    if (idx > -1) { 
     $scope.selection.splice(idx, 1); 
    } 

    // is newly selected 
    else { 
     $scope.selection.push(site); 
    } 
    }; 
}); 
+0

由於角材料中的V 0.9版本,它看起來像上面現在工作的代碼,而@jarz代碼適用於V0.8及以下 – dsal1951 2015-05-22 16:42:32

回答

3

嘗試改變這一點:

ng-checked="selection.indexOf(site) > -1" 

這樣:

ng-checked="{{selection.indexOf(site) > -1}}" 

爲我工作:http://codepen.io/anon/pen/xbNOmE

+1

@jarz答案只是一個更新,因爲他的例子不再工作:http://codepen.io/bora-89/pen/GNXvWJ – bora89 2016-12-12 11:57:00