如何使用角度数组在复选框中显示选中的值?

时间:2015-07-23 12:30:22

标签: javascript jquery angularjs

我已经完成了在主页中选择htc并进入另一页面。现在我想显示所选的商店值和severdata是否匹配(在这种情况下我需要显示true)。在提交事件期间,我想传递所有选定的值。我已经尝试了下面的代码,但它不适用于我。

$scope.Selctedstores =window.localStorage.getItem("selectedservices");
console.log($scope.Selctedstores);
//console i am getting htc

var serverData = ["Nokia", "Htc", "Samsung"];       
    $scope.items = [];
    for (var i = 0; i < serverData.length; i++)
    {
        var modal = {
            name: serverData[i],
            selected: false
        };           
        $scope.items.push(modal);
    }
    $scope.check = function()
    {
        var checkedItems = [];
        for (var i = 0; i < $scope.items.length; i++) {
            if ($scope.items[i].selected) {
                checkedItems.push($scope.items[i].name);
            }
        }
        console.log(checkedItems);
    }

HTML

<div ng-controller="Test1Controller">
    <div ng-repeat="item in items">
        <input type="checkbox" ng-model="item.selected" /> {{item.name}}
    </div>
    <input type="button" name="submit" value="submit" ng-click="check()" />
</div>

2 个答案:

答案 0 :(得分:2)

在推送到项目数组之前,请检查该项目是否已存在于所选商店中。如果是,则将selected选为true。希望这可以帮助。如果您有任何问题,请告诉我

检查更新的fiddle

function TodoCtrl($scope) {
        var serverData = ["Nokia", "Htc", "Samsung"];
        var selectedStore = ["Htc"]
        $scope.items = [];
        for (var i = 0; i < serverData.length; i++)
        {
            var modal = {
                name: serverData[i],
                selected: false
            };
            if (selectedStore.indexOf(serverData[i]) >= 0) {
                modal.selected = true;
            }
            $scope.items.push(modal);
        }
        $scope.check = function()
        {
            var checkedItems = [];
            for (var i = 0; i < $scope.items.length; i++) {
                if ($scope.items[i].selected) {
                    checkedItems.push($scope.items[i].name);
                }
            }
            console.log(checkedItems);
        }
    }

答案 1 :(得分:1)

尝试

for(var i=0;i<serverData.length;i++) { var modal = { name:serverData[i], selected:($scope.Selctedstores !== null && $scope.Selctedstores.indexOf(serverData[i]) > -1) ? true : false };