用数组初始化 Angular 范围变量

问题描述 投票:0回答:1

我正在为我的应用程序使用 AngularJS。我正在将 json 格式的数据传递到 Web API。我在将复选框中的多个选定值从 Angular 控制器传递到 WebAPI 时遇到问题。

这是我的控制器代码

    $scope.target=[];
    $scope.add_workout_a = function(workout){
    for (var i = 0; i < $scope.Target.length; i++) {
            if ($scope.Target[i].Selected) {
                $scope.value = $scope.Target[i].Value;
                console.log($scope.value);//Here i am able to get the 
                value as 0,1,2 if i select 3 values .//
            }
        }

    $scope.cardio_duration=$scope.workout.cardio_duration;
    $scope.primary_muscles=$scope.workout.primary_muscles;
    $scope.target=$scope.value;
    console.log($scope.target);//Here i am not able to get the 
    value.If i select three vales also it is displaying only last
    value that is 2.//

    $scope.time=$scope.workout.selectedTime;
    $scope.days=$scope.workout.selectedDay;

    AdminManageWorkoutService.add_workout_a($scope.cardio_duration,
    $scope.primary_muscles,$scope.target,$scope.time,$scope.days).then(function(response){
    console.log(response);
    //rest of the code
        })
    }   

这是目标列表

    $scope.Target = [{
    Name: 'Target1',
    Value: 0,
    Selected: false
}, {
    Name: 'Target2',
    Value: 1,
    Selected: false
}, {
    Name: 'Target3',
    Value: 2,
    Selected: false
}];

这是目标复选框的 html 代码

    <div class="form-group" data-ng-repeat="target in Target">
    <label for="chkCustomer_{{target.Value}}"><br/>
    <input id="chkCustomer_{{target.Value}}" type="checkbox" data-ng-
    model="target.Selected" />
    {{target.Name}}
    </label>
    </div>
    <button type="submit" class="btn btn-primary" data-ng-
    click="add_workout_a(workout)">Submit</button>

如果我在复选框中选择多个值,它也仅以这种格式显示最后一个值。

     target:2.

但我想以这种格式发送

     target: [0,1,2]

谁能告诉我如何将复选框中的选定值以数组格式获取到 $scope.target 变量中?

angularjs
1个回答
0
投票

首先你必须将

$scope.value
声明为数组

$scope.value=[];

然后

foreach
通过 $scope.target 并使用
push
将适当的属性添加到
$scope.value

尝试关注

$scope.value=[];
angular.forEach($scope.Target ,
  function(item) {
    if (item.Selected)
      $scope.value.push(item.Value);
  }
);
console.log(self.value);
© www.soinside.com 2019 - 2024. All rights reserved.