在angularjs中动态地向复选框添加/移除checked属性

Adding/Removing checked attribute to checkbox dynamiclly in angularjs

本文关键字:添加 移除 checked 属性 复选框 angularjs 动态      更新时间:2023-09-26

如何使用angularjs简单地添加和删除复选框中的checked属性?我已经从这个问题找到了解决方案,但它需要Jquery

有没有其他方法可以做到这一点,而不使用Jquery?

这是我所尝试的

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

但是删除不成功

这是Angularjs推荐的选中和取消选中复选框的方式

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

同样适用

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

你不需要特别的指令,ngChecked会很好地工作:

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>

请查看工作示例:DEMO

HTML

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

控制器:

var app = angular.module('plunker', []);
app.controller('MainCtrl', function($scope) {
    $scope.checkVal = true;
    //for adding/removing checkbox
    $scope.test = function() {
           $scope.checkVal = !$scope.checkVal;
    }
});

我可以跨指令添加动态属性,这可能会帮助你

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

在控制器

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

使用

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