I am new to angular.js and I was trying to create an html list with checkboxes, so what I was trying to achieve was to call a javascript function, when a user checks a checkbox.
<input id='box' ng-model='" + key + "' ng-change='graphquery(\"" + key + "\")' class = 'queryNameList css-checkbox' type = 'checkbox' />
So here, I have used ng-change
which basically captures all changes, it calls function graphquery
on both cases ( checking and unchecking)
Is it possible to specify, condition, like it should only call this function if the checkbox is checked.
I am new to angular.js and I was trying to create an html list with checkboxes, so what I was trying to achieve was to call a javascript function, when a user checks a checkbox.
<input id='box' ng-model='" + key + "' ng-change='graphquery(\"" + key + "\")' class = 'queryNameList css-checkbox' type = 'checkbox' />
So here, I have used ng-change
which basically captures all changes, it calls function graphquery
on both cases ( checking and unchecking)
Is it possible to specify, condition, like it should only call this function if the checkbox is checked.
Share Improve this question asked Jan 12, 2014 at 10:29 user1371896user1371896 2,2507 gold badges26 silver badges32 bronze badges4 Answers
Reset to default 5ng-change="!key || graphQuery(key)"
If the checkbox is checked then !key
resolves to false
, so graphQuery(key)
is executed.
If the checkbox is unchecked then !key
resolves to true
, so anything after ||
is ignored;
$scope.graphquery = function(key){
if(!$scope[key]){
//do nothing
return;
}
//do something
}
Check this example from the documentation.
ngModel on a checkbox seems to either be true
or false
and that's what gets passed to the function that you specify in ngChange
. If you want to specify a truth value or a falseness value, you can use the ngTrueValue
and ngFlaseValue
directives.
See this Plunk.
var app = angular.module('plunker', []);
app.controller('MainCtrl',
function($scope) {
$scope.graphQuery = function(key) {
if (key)
$scope.key = key
}
$scope.returnKey = function() {
return '123'
}
}
)
And in HTML
<body ng-controller="MainCtrl">
<input id='box' ng-model='key' ng-change='graphQuery()' class='queryNameList css-checkbox'
type='checkbox' ng-true-value="{{returnKey()}}" />
<pre>Key: {{key}}</pre>
</body>
So, what you want to do is check if the value of key
is true
or false
and only execute your code when the value is true
and you can specify a function in ng-true-value
to return a string in case of true
.
document.getElementById('box').addEventListener('change', function(){
if(this.checked === true) runMyFunction();
});