0

I have seen various questions here, but they are of ng-checked, which are not relevant to me I guess. I have a fairly simple problem. Here's my HTML.

<label><input type="checkbox" value="" ng-checked="dothis" id="alcohol">Serves alcohol</label>

I am not sure how to wrap the function in angular if its checked. Basically it should be like.

if(checked){
//do this
}
else{
//do that
}

2 Answers 2

3

use ngModel and ngChange

<input type="checkbox" ng-model="foo" ng-change="fooChanged()" />

//in controller
$scope.foo = false;
$scope.fooChanged = function(){
    if($scope.foo){
        ...
    }else{
        ...
    }
}
Sign up to request clarification or add additional context in comments.

1 Comment

@Ajiaz, you're welcome, could you mark it as answer?
0

Use ngModel to bind the value two way.

While ngChange is an optional.

Please find the documentation here: https://docs.angularjs.org/api/ng/input/input%5Bcheckbox%5D

Please find the working demo below

<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<script>
  angular.module('checkboxExample', [])
    .controller('ExampleController', ['$scope', function($scope) {
      $scope.checkboxModel = {
       value1 : true,
       value2 : 'YES'
     };
    }]);
</script>
<form ng-app="checkboxExample" name="myForm" ng-controller="ExampleController">
  <label>Value1:
    <input type="checkbox" ng-model="checkboxModel.value1">
  </label><br/>
  <label>Value2:
    <input type="checkbox" ng-model="checkboxModel.value2"
           ng-true-value="'YES'" ng-false-value="'NO'">
   </label><br/>
  <tt>value1 = {{checkboxModel.value1}}</tt><br/>
  <tt>value2 = {{checkboxModel.value2}}</tt><br/>
 </form>

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.