【问题标题】:Select checkbox from array values in AngularJS从AngularJS中的数组值中选择复选框
【发布时间】:2016-09-23 15:29:44
【问题描述】:

我创建了一个页面,其中包含一些文本框、单选按钮和复选框。我正在使用此页面来保存新数据或编辑现有数据。我可以保存新数据,但为了编辑数据,页面应该显示一些从变量中获取的预定义值。我能够从该变量获取和设置文本框和单选按钮的值。但我无法选中复选框。我有很多复选框,所以我使用 ng-repeat 来显示页面上的值。我正在将选定复选框的值设置为一个数组并将该值传递给我的服务层。

下面是我的代码sn-ps:

HTML:

<div id="activityCheckboxList" class="checkboxList">
    <div ng-repeat="activity in activities">
        <label>
                <input type="checkbox" ng-true-value="activity" ng-checked="selection.indexOf(activity) > -1" ng-click="toggleSelection(activity)"/>
                <span>{{activity.activityName}}</span>
            </label>
    </div>
</div>

app.js:

$scope.selection=[];
$scope.getActivities(); //this sets values in $scope.activities which is a     list coming from service layer

    //Get Selected Activities from Check Boxes
    $scope.toggleSelection = function toggleSelection(activity){
        var idx = $scope.selection.indexOf(activity);

        if(idx > -1){
            $scope.selection.splice(idx, 1);
        }
        else{
            $scope.selection.push(activity);
        }
    };

在此之后,在单击提交时,我传递了 $scope.selection,其中将包含我的活动对象。

为了编辑数据,我可以将数据放在 selection[] 中。但是如何使用它来检查复选框,之后用户应该再次取消选中/选中它们。我尝试使用 foreach 循环,但没有帮助。

提前致谢

【问题讨论】:

    标签: html angularjs arrays


    【解决方案1】:

    由于“活动”是一个对象,因此 indexOf 不是找到索引的正确方法。我对您的代码做了一些更改

    html

                    <input type="checkbox" ng-true-value="activity" 
           ng-checked="checkInSelectionList(activity)" ng-click="toggleSelection(activity)"/>
                    <span>{{activity.activityName}}</span>
    

    js

    $scope.checkInSelectionList = function (item) {
    for(var i=0; i<$scope.selection.length;i++){
        if($scope.selection[i]['ID'] == item['ID']){
        return true;
      }
    }
    }
    

    您也可以使用underscore 来查找对象的索引。

    https://jsfiddle.net/nors536b/

    【讨论】:

    • 非常感谢!你真的帮助节省了很多时间。 :)
    猜你喜欢
    • 1970-01-01
    • 2018-01-13
    • 1970-01-01
    • 1970-01-01
    • 2016-07-26
    • 1970-01-01
    • 2015-06-27
    • 2018-03-25
    • 2018-05-07
    相关资源
    最近更新 更多