最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - Call function only when check box is checked - Stack Overflow

programmeradmin1浏览0评论

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 badges
Add a ment  | 

4 Answers 4

Reset to default 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;

$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();
});
发布评论

评论列表(0)

  1. 暂无评论