0

I want the $scope.selectedRecords variable to increment when a checkbox is checked. Right now nothing appears to happen, meaning the {{selectedRecords}} doesn't increment. There is no change.

Controller:

$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)">
3
  • Have you tried using ng-change instead of ng-click ? What does not work exactly ? Could you provide a CodePen that reproduces the error ? :-) Commented Sep 27, 2015 at 17:05
  • @LoremIpsum I have tried ng-change with the same result. I updated my OP with more info and I will work on a code-pen now. Commented Sep 27, 2015 at 17:08
  • Is your checkbox in an ng-repeat ? Commented Sep 27, 2015 at 17:16

2 Answers 2

1

Here's a working example : http://codepen.io/anon/pen/pjNWVL?editors=101

Can't really understand why your sample doesn't work, but mine might give you some help :-)

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;
    }
  };
});
Sign up to request clarification or add additional context in comments.

Comments

0

The problem is that you have not defined record on the scope. If you add something like this to your controller:

$scope.record = {};

Then things should work.

Now, if you are in an ng-repeat block, things will be more complicated.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.