1

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.

4 Answers 4

5
ng-change="!key || graphQuery(key)"

If the checkbox is checked then !keyresolves to false, so graphQuery(key) is executed.

If the checkbox is unchecked then !key resolves to true, so anything after || is ignored;

Sign up to request clarification or add additional context in comments.

Comments

1
$scope.graphquery = function(key){
  if(!$scope[key]){
   //do nothing
   return;
  }

//do something
}

Comments

0

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.

Comments

-4
document.getElementById('box').addEventListener('change', function(){ 
if(this.checked === true) runMyFunction();
});

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.