Reputation: 2230
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.
Upvotes: 1
Views: 10774
Reputation: 26828
ng-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;
Upvotes: 5
Reputation: 7019
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
.
Upvotes: 0
Reputation: 10121
$scope.graphquery = function(key){
if(!$scope[key]){
//do nothing
return;
}
//do something
}
Upvotes: 1
Reputation: 136
document.getElementById('box').addEventListener('change', function(){
if(this.checked === true) runMyFunction();
});
Upvotes: -4