Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Adding/Removing checked attribute to checkbox dynamiclly in angularjs

How can i simply add and remove checked attribute to check-box using angularjs. I've find solution from this question,but it requires Jquery

Is any other way to do this without using Jquery?

Here is what i am tried

<input type="checkbox" id="test"  class="switch__input" checked="{{checkVal}}">
<input type="button" ng-click="test()" value="test">

JS

 module.controller('settingsCtrl',function($scope){
  //for adding
  $scope.checkVal="checked";
  //for removing checkbox
  $scope.test=function(){
   $scope.CheckVal="";
  }
}

But the removing wont work

like image 746
shellakkshellu Avatar asked Aug 13 '15 06:08

shellakkshellu


3 Answers

This is Angularjs recommended way of check and un check checkbox

HTML : <input type="checkbox" ng-model="checkVal" ng-true-value="true" ng-false-value="false">

Also works

<input type="checkbox" ng-checked="checkVal">

JS :

module.controller('settingsCtrl',function($scope){
  //for adding
  $scope.checkVal=true;
  //for removing checkbox
  $scope.test=function(){
   $scope.checkVal=false;
  }
}
like image 90
venkat7668 Avatar answered Nov 12 '22 18:11

venkat7668


You don't need special directive for this, ngChecked would work well:

var app = angular.module('demo', []).controller('MainController', function($scope) {
  $scope.checkVal = true;

  $scope.test = function() {
    $scope.checkVal = !$scope.checkVal; // or false
  };
});
<script src="https://code.angularjs.org/1.4.3/angular.js"></script>
<div ng-app="demo" ng-controller="MainController">
    <input type="checkbox" id="test" class="switch__input" ng-checked="checkVal">
    <input type="button" ng-click="test()" value="test">
</div>
like image 44
dfsq Avatar answered Nov 12 '22 18:11

dfsq


Please check working example : DEMO

HTML

<input type="checkbox" id="test" class="switch__input" ng-checked="checkVal">
<input type="button" ng-click="test()" value="test">

Controller:

var app = angular.module('plunker', []);

app.controller('MainCtrl', function($scope) {

    $scope.checkVal = true;
    //for adding/removing checkbox
    $scope.test = function() {
           $scope.checkVal = !$scope.checkVal;
    }
});
like image 30
User2 Avatar answered Nov 12 '22 18:11

User2