Pass checkbox value to angular's ng-click
Asked Answered
C

5

27

Is there a way to pass to angular directive ng-click the value of the associated input?

In other words, what should replace this.value in the following:

<input type="checkbox" id="cb1" ng-click="checkAll(this.value)" />

PS. I don't want a workaround to alternate values, I just wonder if is possible to pass a value of an input as argument to an angular function.

Chengtu answered 30/10, 2015 at 8:28 Comment(3)
Can you please add some more code what in you want in checkAllMagdalenemagdalenian
add a model on input and pass it in methodFrampton
Possible duplicate of Angular checkbox and ng-clickHippocras
N
44

You can do the following things:

  • Use ng-model if you want to bind a html component to angular scope
  • Change ng-click to ng-change
  • If you have to bind some value upon checking and un-checking the checkbox use ng-true-value="someValue" and ng-false-value="someValue"

The order of execution of ng-click and ng-model is ambiguous since they do not define clear priorities. Instead you should use ng-change or a $watch on the $scope to ensure that you obtain the correct values of the model variable.

Courtesy of musically_ut

Working Demo

<input type="checkbox" id="cb1" ng-model="check" ng-change="checkAll(check)" ng-true-value="YES" ng-false-value="NO"/> Citizen
Nunnally answered 30/10, 2015 at 8:40 Comment(0)
S
12

Today i wanted to do the same thing and i see nobody answered the actual question. This is against the Angular philosophy, but you can replace "this.value" with "$event.target.checked" :

<input type="checkbox" id="cb1" ng-click="checkAll($event.target.checked)" />
Spleen answered 3/11, 2017 at 13:10 Comment(2)
$event is undefined in a checkbox on ng-change unfortunatelyJoejoeann
Pass $event and then in function var checkbox = $event.target.checked works.Stepdaughter
S
2

Assigning an ng-model to it will return boolean value depending upon the change to it:

<input type="checkbox" id="cb1" ng-model="checkValue" ng-change="checkAll(checkValue)" />

Better to use ng-change rather than ng-click

Superannuated answered 30/10, 2015 at 8:32 Comment(2)
There is no much sense to pass the checkValue as argument, cause it anyway available in the model...Chengtu
@Serge Yes there is, it allows you to control the flow of data, and if someone else has to read the code it will be much easier to understand where does that data came from.Boiardo
T
2

Bind the checkbox to a value and pass it to ng-click.

<input type="checkbox" ng-model="value" id="cb1" ng-click="checkAll(value)" />
Tubule answered 30/10, 2015 at 8:34 Comment(0)
C
0

You can do the following things. Worked for me.

<input type="checkbox" id="cb1" ng-click="onChecked($event.target.checked)" />
Catholicon answered 11/2, 2021 at 13:17 Comment(1)
event will be undefined hereSpindly

© 2022 - 2024 — McMap. All rights reserved.