简体   繁体   中英

How to call a function from a AngularJS directive with checkbox, when it is checked?

Recently I have implemented a directive which uses a checkbox customized with css. I need to call a function from a scope when the value of checkbox is checked. I've got something working with ng-click but this is not what I am searching for.

I looked into ng-true-value , but it expects a value, not a function I can invoke. Is there any way to solve this so the function can be called only when checkbox is active? This is the directive definition:

{
    restrict: 'E',
    replace: true,
    require: ['^ngModel'],
    scope:{ 
            isChecked: '=?', 
            secondFunction: '&'
          },
    template: function (elem, attr){
      var a= '<label class="switch"'+attr.class+'><input type="checkbox" ng-class="{checked: isChecked}"><i></i></label>';
      return a;    
    }, 
} 

Plunk with a directive

use ng-change = 'functionName()' on chechkbox

Reference:

you can use ng-model and watch function to perform logics on checking checkboxes

$scope.$watch('modelName', function() {
    // do something here

});

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM