问题描述
我曾问一个关于问题
How在angularjs 使用NG选项作为模型对象相关联。
I had asked a question aboutHow to associate objects as models using ng-options in angularjs.
和我有一个真棒答案非常快。我的后续问题是,响应使用<选择多发方式>
来处理子对象数组
And I got an awesome answer very fast. My followup questions is that the response uses <select mutiple>
to handle the child object array.
您可以看到我想要的工作例如,&LT工作;选择&GT;
在<一个href=\"http://plnkr.co/edit/FQQxrSE89iY1BnfumK0A?p=$p$pview\">http://plnkr.co/edit/FQQxrSE89iY1BnfumK0A?p=$p$pview
You can see a working example of what I want, working with <select>
at http://plnkr.co/edit/FQQxrSE89iY1BnfumK0A?p=preview
如何使用&LT;输入类型=复选框'&GT;
(而不是&LT;选择&GT;
)来处理对象数组即 NG:模型=shirt.colors
而重复从颜色的项目
对象数组
How can I use <input type='checkbox'>
(instead of <select>
) to handle that object array i.e. ng:model="shirt.colors"
while repeating the items from colors
object array.
究其原因,这似乎太复杂对我来说,我必须要管理的对象,而不是值数组...例如,如果你在捣鼓看,有颜色对象和
衬衫
对象。
The reason, this appears so complicated to me is that I have to manage an array of objects instead of array of values... for example, if you look in the fiddle, there are color
objects and shirt
object that has multiple colors.
如果在颜色
对象的变化,应该改变相应的颜色
的对象。
对象恤
If the color
object changes, it should change the corresponding color
objects in shirt
objects.
感谢您提前。
推荐答案
您只需要在你的范围内一些中间值,并绑定复选框它。在您的控制器 - 注意它的变化,并手动重建shirt.colors,根据其值
You just need some intermediate value in your scope, and bind checkboxes to it. In your controller - watch for it changes, and manually reconstruct shirt.colors, according to it value.
<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);
您可以在这里进行测试:<一href=\"http://plnkr.co/edit/lh9hTa9wM5fkh3nT09RJ?p=$p$pview\">http://plnkr.co/edit/lh9hTa9wM5fkh3nT09RJ?p=$p$pview
You can test it here: http://plnkr.co/edit/lh9hTa9wM5fkh3nT09RJ?p=preview
这篇关于使用复选框以angularjs来管理对象的数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!