2013-02-09 50 views
11

我曾問過一個關於 How to associate objects as models using ng-options in angularjs的問題。使用angularjs中的複選框來管理對象數組

我得到了一個非常快的真棒回答。我的後續問題是,響應使用<select mutiple>來處理子對象數組。

你可以看到我想要什麼工作的例子,在http://plnkr.co/edit/FQQxrSE89iY1BnfumK0A?p=preview

<select>工作,我如何使用(而不是<select><input type='checkbox'>來處理對象數組即ng:model="shirt.colors"而從colors對象數組重複的項目。

原因,這對我來說顯得如此複雜是我必須管理一個對象數組而不是數組數組......例如,如果你在小提琴中看,有color對象和shirt對象多種顏色。

如果color對象發生變化,則應該更改shirt對象中對應的color對象。

預先感謝您。

回答

18

你只需要在你的範圍中的一些中間值,並將複選框綁定到它。在你的控制器中 - 監視它的變化,並根據它的價值手動重建shirt.colors。

<div ng-repeat='shirt in shirts'> 
    <h3>Shirt.</h3> 
    <label>Size: <input ng-model='shirt.size'></label><br/> 
    <label>Colors:</label> 
    <label ng-repeat="color in colors"> 
    {{color.label}} <input ng-model="selection[$parent.$index][$index]" type="checkbox"/> 
    </label> 

    </label> 
</div> 

而在你的控制器:

$scope.selection = [[],[]]; 
$scope.$watch('selection', function() { 
    console.log('change', $scope.selection); 
    angular.forEach($scope.selection, function (shirtSelection, index) { 
    $scope.shirts[index].colors = []; 
    angular.forEach(shirtSelection, function (value, index2) { 
     if (value) $scope.shirts[index].colors.push($scope.colors[index2]); 
    }); 
    }); 
}, true); 

你可以在這裏進行測試:http://plnkr.co/edit/lh9hTa9wM5fkh3nT09RJ?p=preview

+0

謝謝。這正是我一直在尋找:) – 2013-02-10 16:26:23

+0

這是輝煌的,非常感謝! – 2014-07-23 16:55:15

+1

真棒 - 好主意!除了使用Pythonic的概念外,我還使用了第三方指令,這有助於簡化處理Angular的複選框的方法。 http://vitalets.github.io/checklist-model/ – ClearCloud8 2014-12-18 23:33:01