【问题标题】:angularjs get only selected checkboxangularjs 只获取选中的复选框
【发布时间】:2016-08-07 05:25:11
【问题描述】:

我想在我的循环中获取选中的复选框,对于该复选框,我必须在点击时检索金额字段。

这是我的 HTML 脚本:

<div ng-repeat="$item in items">
    Amount  :<input ng-model="$item.daily_data.payment_amount">
    Check  : <input type=checkbox ng-model="checkAmount[$item.daily_data.id]" ng-value="$item.id" >
</div>

<input type="button" ng-click="checkNow()" />

以下脚本显示所有复选框。我想要唯一选择的一个。

JS 脚本:

$scope.checkAmount = {};
$scope.checkNow(){
console.log($scope.checkAmount);
}

【问题讨论】:

  • 你在ngRepeat里面吗?
  • 是的。在 ngRepeat 中
  • 更新问题,希望你能看到修改。有什么解决办法吗?
  • 是的,看我的回答..

标签: angularjs checkbox


【解决方案1】:

首先要使用functions$scope,你应该这样做:

$scope.checkNow = function() {
  ...
}

$scope.checkNow = checkNow;

function checkNow() {
  ...
}

关于您的问题:

您可以将checkboxes 绑定到一个属性(类似于checked),这样您就可以轻松地在controller 中拥有checked 的项目。

然后,要计算所有checked金额的total,我建议你使用Array.prototype.filter() + Array.prototype.reduce()

这是一个基于您的原始 code演示

(function() {
  angular
    .module("app", [])
    .controller('MainCtrl', MainCtrl);

  MainCtrl.$inject = ['$scope'];

  function MainCtrl($scope) {
    $scope.checkNow = checkNow;
    $scope.checkAmount = {};
    $scope.items = [
      {
        "id": 1
      }, 
      {
        "id": 2
      },
      {
        "id": 3
      }
    ];

    function checkNow() {
      $scope.total = $scope.items.filter(function(value) {
        return value.checked;
      }).reduce(function(a, b) {
        return a + b.amount;
      }, 0);
    }
  }
})();
<!DOCTYPE html>
<html ng-app="app">

<head>
  <script src="https://cdnjs.cloudflare.com/ajax/libs/angular.js/1.5.8/angular.min.js"></script>
</head>

<body ng-controller="MainCtrl">
  <div ng-repeat="$item in items">
    <label>
      Amount: <input type="number" ng-model="$item.amount">
    </label>
    <label>
      Check: <input type=checkbox ng-model="$item.checked">
    </label>
  </div>

  <button type="button" ng-click="checkNow()">Check now</button>
  <hr>
  <label for="total">Total</label>
  <input type="number" id="total" disabled ng-model="total">
</body>

</html>

【讨论】:

  • 如果我在此级别的金额和 ID 为 $item.daily_data.payment_amount
  • 我没听懂..你能详细说明一下吗?
  • 当然,我会这样做的。请给我一分钟。
  • 我确实更改了 amount 和 id 字段模型。在我的应用程序中使用。你能在你的答案中做同样的改变吗?
  • 感谢您的宝贵时间。您的解决方案真的很有帮助。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2021-09-11
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2015-02-12
  • 2017-10-04
  • 1970-01-01
相关资源
最近更新 更多