user6656728
user6656728

Reputation:

ng-click for checkbox angularjs

I am creating a web app in which i am getting expense information in my table now if there are 10 data

1)100

2)200

3)300

4)200

5)300

6)400

7)500

8)600

9)900

10)200

all these data will be shown to the user with each data having a checkbox like

<td>{{a.salary}}</td>
<td><input type="checkbox" ng-click="updatefunction(a)" />

and my checkbox is calling a controller of angularjs

$scope.updatefunction = function (param) {
            $scope.updateparam = param;
            console.log($scope.updateparam.salary);
            $scope.totalsalary = Number($scope.totalsalary) + Number($scope.updateparam.salary);
            console.log($scope.totalsalary);
        }

on ng-click this controller will be called but if a user click twice the value is incrementing two times and if i used ng-checked (1 to 10) all the entries are being incremented, what i need to do, i want to increment but if a user unchecked or click multiple times(the value should be decrease),

Upvotes: 0

Views: 1544

Answers (2)

Aravinthan K
Aravinthan K

Reputation: 1861

You need to set a flag for your checkbox field(ng-model).

HTML

<input type="checkbox" ng-model="exp.checked" 
             data-ng-click="calculateTotal(exp)"/>{{exp.salary}}

JS

$scope.calculateTotal = function(exp){
    if(exp.checked){
      $scope.total += exp.salary;
    }else{
      $scope.total -= exp.salary;
    }
  }

Your solution is here

Upvotes: 1

Jitendra gupta
Jitendra gupta

Reputation: 108

You need to use ng-model inside your checkbox

<td><input type="checkbox" ng-click="updatefunction(a)" ng-model="a.checked" />

Initially In your controller set

a.checked=false;

because all the check boxes are unchecked

$scope.updatefunction = function (param) {
if(param.checked){
            $scope.updateparam = param;
            console.log($scope.updateparam.salary);
            $scope.totalsalary = Number($scope.totalsalary) + Number($scope.updateparam.salary);
            console.log($scope.totalsalary);
}else{
     $scope.totalsalary = Number($scope.totalsalary)  -Number($scope.updateparam.salary);

}
        }

Hope this will solve your problem . if in last after reloading page your checked value is not checked and any check box is already checked then make checked =false in last

Upvotes: 0

Related Questions