使用angular获取所有选中的复选框及其关联的属性

时间:2013-05-11 03:54:48

标签: javascript angularjs angularjs-directive

我需要将选中的复选框捆绑在一起以POST到我的服务器。在每个复选框的属性中,我存储了两个重要的值:“pos”(词性)和定义。我需要遍历每个复选框,将其推送到JSON数组,并在按下“添加单词”按钮时将其发送出去。

<input type="checkbox" name="definition-checkbox" pos="noun" definition="Hill, rolling grassland" class="ng-valid ng-dirty">

我已经考虑过将复选框转换为元素限制指令并以某种方式在那里做某些事情,但我不知道如何在这里获取所有值,而不是通过它们进行一些循环所有看起来非Angular 。

有什么建议吗?

Prototype

1 个答案:

答案 0 :(得分:4)

很难判断posdefinition属性中的字符串来自哪里,但是使用Angular,您希望您的视图反映在范围内可访问的某些数据 - 更改在您的视图中(例如,选中一个框)应该更改您范围内的一些数据。

在这种特殊情况下,我希望在对象上看到posdefinition;也许控制器可以访问它们的数组。

app.controller('WordController', function($scope) {
  $scope.word = 'property';

  // Maybe this array came from an $http call; maybe it was injected
  // into the page with `ngInit` or `$routeProvider`.
  // The point is, the controller has a client-side representation of
  // the data you want to show *and manipulate* in the view.
  $scope.definitions = [
    { checked: false, pos: 'noun', definition: 'Something that is owned' },
    { checked: false, pos: 'noun', definition: 'A piece of real estate, such as a parcel of land' },
    { checked: false, pos: 'noun', definition: 'real estate; the business of selling houses' },
    { checked: false, pos: 'noun', definition: 'The exclusive right of possessing, enjoying and disposing of a thing' }
    // ...
  ];
});

既然此信息在范围内,您可以轻松地在视图中绑定它:

<div ng-repeat='definition in definitions'>
  <input type='checkbox' ng-model='definition.checked'> {{definition.definition}}
</div>
<input type='submit' ng-click='submitDefinitions()' value='Add Word'>

由于复选框在单击时直接修改每个定义的.checked属性,因此控制器上的submitDefinitions方法可以轻松确定选择了哪些定义:

app.controller('WordController', function($scope) {
  // ...

  $scope.submitDefinitions = function() {
    var selectedDefinitions = $scope.definitions.filter(function(def) {
      return def.checked;
    });
    // do something with selected definitions
  };
});

这是一个演示基本技术的JSFiddle:http://jsfiddle.net/BinaryMuse/cTBm4/