简体   繁体   中英

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

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;
  }
}

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> 

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;
    }
});

I can across a directive to add dynamic attribute may be this can help you

  myApp.directive('dynAttr', function() {
return {
    scope: { list: '=dynAttr' },
    link: function(scope, elem, attrs){
        for(attr in scope.list){
            elem.attr(scope.list[attr].attr, scope.list[attr].value);   
        }
        //console.log(scope.list);           
    }
};
});

In the controller

$scope.attArray = [
{ attr: 'myattribute', value: '' }
];

Use it as

<input dyn-attrs="attArray"></input>

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