【问题标题】:How to get checked values from checkbox using Angular JS如何使用Angular JS从复选框中获取选中值
【发布时间】:2017-04-24 06:19:13
【问题描述】:

我是 Angular JS 的新手。我有以下复选框,数据来自网络服务:

 <label ng-repeat="r  in MedicalConditions track by $index">
    <input ng-model="ids[$index]" type="checkbox" ng-checked="r.value"> 
       {{r.conditions_name}}
    </label>

console.log 中的值完全符合我的要求。如何将值推送到数组,即 arr[] 并将其字符串化。我试过这样的代码..

//获取医疗条件列表

$scope.parameter = "{}";
$scope.class0 = "{}";
$http.get('http://192.168.1.129:8080/apartment//member/medical/conditions/list').then(function(response) {
    $scope.MedicalConditions = response.data.list;
});

  $scope.$watchCollection('ids', function(newVal) {     
       $scope.parameter.class0 = $scope.ids;
    }); 


$scope.alertdata = function() {
    var parameter = {
        "first_name": $scope.first_name,

        "role": [{
            "role_id": 1,
            "name": "Admin",
            "details": "text"
        }],
        "associated": [{
            "associated_id": 1,
            "associated_name": "Parent",
            "primary_member_id": 1
        }],
        "class0": $scope.ids
    }
    parameter = JSON.stringify(parameter);

【问题讨论】:

  • @Sinchan $scope.lists[] 在我的案例中分配,数据来自动态..在我的案例中该怎么做..
  • 你能做一个小提琴吗?
  • 您应该先尝试使用 ng-model 绑定动态复选框值。然后其他事情会更容易做。

标签: javascript angularjs arrays json


【解决方案1】:

这可能会有所帮助:

angular.module('app', [])
  .controller('Controller', function($scope) {
  
  $scope.ids = {};
  $scope.arr = {};
  
  $scope.MedicalConditions = {};
  
  $scope.MedicalConditions[0] = {};
  $scope.MedicalConditions[0].value= true;
  $scope.MedicalConditions[0].conditions_name= 'first value';
  
  $scope.MedicalConditions[1] = {};
  $scope.MedicalConditions[1].value= false;
  $scope.MedicalConditions[1].conditions_name= 'seconde value';
   
    $scope.$watchCollection('ids', function(newVal) {     
       $scope.parameter.class0 = $scope.ids;
    });
    
    
    $scope.parameter = {};
    $scope.parameter.firstname = 'dummy name';
    $scope.parameter.class0 = $scope.ids;
    

  });
<!DOCTYPE html>

<head>
  <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
  <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>

  <script src="script.js"></script>
</head>

<body ng-app="app">
  <div ng-controller="Controller">


    <label ng-repeat="r  in MedicalConditions track by $index">
     <input ng-model="ids[$index]" type="checkbox" ng-checked="r.value" > {{ r.conditions_name}}
     </label>
  
  
  <br>
  
  Parameter: {{parameter}}


  </div>
</body>

</html>

【讨论】:

  • 感谢您的帖子。您已分配值 $scope.MedicalConditions[0].conditions_name= 'first value';像那样。但在我的情况下,数据是从 Web 服务动态传输的。在我的情况下该怎么做。?
  • @PrashanthHarish 只是为了让 sn-p 工作。当您通过 $http 服务获取数据时,您可以分配变量。
  • 为什么要尝试将值推送到 arr 中,您可以在 ids 模型中获取值,正如您在上面的工作 sn-p 中看到的那样
  • TypeError:无法设置未定义的属性“class0”。错误即将来临...
  • @PrashanthHarish 可能是因为您没有初始化参数变量。您必须第一次将其定义为对象。
【解决方案2】:

尝试如下...

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

app.controller('ctrl', function($scope){
$scope.ids = [];
$scope.arr = [];
$scope.checkSelected = [];
$scope.MedicalConditions = [{"conditions_name":"xxz","conditions_id":"1"}, {"conditions_name":"yyz","conditions_id":"2"}, {"conditions_name":"zzz","conditions_id":"3"}];
$scope.$watchCollection('ids', function(newVal) {       
  for (var i = 0; i < newVal.length; ++i) {
    console.log(newVal[i]);
    $scope.arr.push(newVal[i]);       
}
});

$scope.checkAllR = function () {
            $scope.checkAll = !$scope.checkAll;

            if ($scope.checkAll) {
                $scope.checkSelected = [];
                angular.forEach($scope.MedicalConditions, function (checkR) {                   
                   
                        checkR.check = $scope.checkAll;
                        $scope.checkSelected.push(checkR);
                   
                });
            }
            else {
               $scope.checkSelected = [];
                angular.forEach($scope.MedicalConditions, function (checkR) {
                    var idx = $scope.checkSelected.indexOf(checkR);
                    checkR.check = $scope.checkAll;
                    $scope.checkSelected.splice(idx, 1);
                });
            }
        };

$scope.addChecked = function (checked) {
            if ($scope.checkSelected == undefined || $scope.checkSelected == null) {
                $scope.checkSelected = [];
            }

            var idx = $scope.checkSelected.indexOf(checked);

            // delete if exists
            if (idx > -1) {
                $scope.checkSelected.splice(idx, 1);
                checked.check = false;
            }
                // add
            else {
                $scope.checkSelected.push(checked);
                checked.check = true;               
            }       
$scope.checkAll = $scope.checkSelected.length == $scope.MedicalConditions.length ? true : false;
        };
var parameter = {
   "first_name": $scope.first_name,
   "middle_name": $scope.middle_name,
   //"class0": /*stringified data i.e., arr[] */ 
};
});
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.4.8/angular.min.js"></script>
<body ng-app="exApp" ng-controller="ctrl">
 Select All : <input type="checkbox" name="checkbox" value="1" ng-checked="checkAll" ng-click="checkAllR()"><br>
<label ng-repeat="r  in MedicalConditions">
<input type="checkbox" name="checkbox" class="check-nolabel" value="1" ng-checked="r.check" ng-click="addChecked(r)"> {{ r.conditions_name}}
 </label><br><br>
 {{checkSelected}}
 </body>

【讨论】:

    【解决方案3】:

    希望这会有所帮助。

    <div ng-app="myApp" ng-controller="MyCtrl">
        <label ng-repeat="r in MedicalConditions track by $index">
        <input ng-model="ids[$index]" 
          ng-init="ids[$index] = r.value"
          type="checkbox"> 
        {{r.condition}}
      </label>
    </div>
    

    这是你的控制器。

    var myApp = angular.module('myApp', []);
    
    myApp.controller('MyCtrl', function($scope){
        $scope.ids = [];
    
        $scope.MedicalConditions = [{
        _id: 1,
        value: true,
        condition: 'Condition 1'
      }, {
        _id: 2,
        value: false,
        condition: 'Condition 2'
      }, {
        _id: 3,
        value: true,
        condition: 'Condition 3'
      }];
    });
    

    JsFiddle

    【讨论】:

    • 感谢您的帖子。我自己解决了这个查询..:)
    【解决方案4】:
    <label ng-repeat="r  in MedicalConditions track by $index">
    <input ng-model="ids[$index]" type="checkbox" ng-change="valCh(r)"> {{r.conditions_name}}
    </label>
    

    控制器代码如下所示:

    var postApp = angular.module('EntityApp', []);
    postApp.controller('EntityAppCntroller', function($scope, $http, $window, $timeout, $location) {
    
        //To fetch Medical Conditions List    
            $http.get('http://111.222.444:8080/apartment//member/medical/conditions/list').then(function(response) {
                $scope.MedicalConditions = response.data.list;
            });
            var list = [];
            $scope.valCh = function(value) {
                list.push(value);
                JSON.stringify(list);
            }
    
            $scope.alertdata = function() {
                var parameter;
                parameter = {
                    "parameter": {
                        "first_name": $scope.first_name,
                        "medicalconditions": list
                    }
                }
                $http({
                    url: 'http://111.222.333:8080/apartment//save/member/details',
                    method: 'POST',
                    headers: {
                        'Content-Type': 'application/json'
                    },
                    data: JSON.stringify(parameter)
                }).success(function(data, status) {
                    if (data.status == 'success') {
                        alert("User Created");
                        $location.reload();
                    } else if (data.status == 'failure') {
                        alert("Some failure please try again later !!!");
                    }
                });
            };
        });
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2016-01-03
      • 2017-12-12
      • 1970-01-01
      • 2019-08-30
      • 1970-01-01
      • 1970-01-01
      • 2012-04-08
      相关资源
      最近更新 更多