Pass checkbox value to angular's ng-click

◇◆丶佛笑我妖孽 提交于 2020-07-17 03:49:45

问题


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.


回答1:


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



回答2:


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)" />



回答3:


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




回答4:


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

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


来源:https://stackoverflow.com/questions/33431591/pass-checkbox-value-to-angulars-ng-click

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!