选中复选框时增加变量 - 角度

时间:2015-09-27 16:57:51

标签: angularjs

我希望$scope.selectedRecords变量在选中复选框时递增。现在似乎没有任何事情发生,这意味着{{selectedRecords}}没有增加。没有变化。

控制器:

$scope.selectedRecords = 0;

// SET-UP ROW CLICK FOR CHECKBOX
$scope.setSelected = function(record) {

  if (!record.Selected) {
    record.Selected = true;
    $scope.selectedRecords += 1
  } else {
    record.Selected = false;
    $scope.selectedRecords -= 1

  }
}

HTML:

<h4>{{selectedRecords}} users selected</h4>
<tr ng-repeat="record in records | orderBy:sortType:sortReverse | filter:searchUsers" ng-class="class" class="row-link" ng-click="setSelected(record)">
<input type="checkbox" ng-model="record.Selected" ng-click="setSelected(record)">

2 个答案:

答案 0 :(得分:1)

以下是一个工作示例:http://codepen.io/anon/pen/pjNWVL?editors=101

无法理解为什么你的样本不起作用,但我的可能会给你一些帮助: - )

HTML:

<div ng-app="pouet" ng-controller="PouetCtrl">
  <h4>{{selectedRecords}} users selected</h4>
  <div  ng-repeat="record in records">
    <input type="checkbox" ng-model="record.selected" ng-click="setSelected(record)">
    <span class="label">{{record.label}}</span>
  </div>
</div>

JS:

var mod;

mod = angular.module('pouet', []);

mod.controller('PouetCtrl', function($scope) {
  $scope.records = [
    {
      selected: false,
      label: 'foo'
    }, {
      selected: true,
      label: 'bar'
    }, {
      selected: true,
      label: 'baz'
    }
  ];

  $scope.selectedRecords = ($scope.records.filter(function(record) {
    return record.selected;
  })).length;

  $scope.setSelected = function(record) {
    if (record.selected) {
      record.Selected = true;
      $scope.selectedRecords += 1;
    } else {
      record.selected = false;
      $scope.selectedRecords -= 1;
    }
  };
});

答案 1 :(得分:0)

问题是您尚未在范围上定义record。如果你向你的控制器添加这样的东西:

$scope.record = {};

然后事情应该有效。

现在,如果您处于ng-repeat块中,事情会更复杂。