使用复选框以angularjs来管理对象的数组 [英] Use checkboxes in angularjs to manage array of objects

查看:106
本文介绍了使用复选框以angularjs来管理对象的数组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我曾问一个关于问题
<一href=\"http://stackoverflow.com/questions/14751674/how-can-i-associate-objects-as-models-using-ng-options-in-angularjs/14753629\">How在angularjs 使用NG选项作为模型对象相关联。

I had asked a question about How to associate objects as models using ng-options in angularjs.

和我有一个真棒答案非常快。我的后续问题是,响应使用&LT;选择多发方式&gt; 来处理子对象数组

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.

究其原因,这似乎太复杂对我来说,我必须要管理的对象,而不是值数组...例如,如果你在捣鼓看,有颜色<数组有多种颜色/ code>对象和衬衫对象。

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来管理对象的数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆