使用数组初始化Angular范围变量

时间:2017-12-13 04:38:33

标签: angularjs

我正在为我的应用程序使用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
}];

以下是Target复选框的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变量?

1 个答案:

答案 0 :(得分: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);