如何根据angularjs中的数据自动选择复选框?

时间:2016-12-09 07:43:02

标签: angularjs

在我的webapp中,有一个复选框列表。我需要的是,从后端我得到一个数据存在的列表,根据这些数据,我想自动选中复选框。如果它混淆了下面是我的代码。

HTML

     $scope.selectDays = ['Sun', 'Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat'];

控制器

    ["SUN", "MON"];

从后端我收到的数据低于响应

$scope.selectDays
下面是

分享我页面的快照。 enter image description here

我需要检查响应数据class SmartCarrier{ private: string carrier_name_; map<string,vector<Message*>> accounts_map; public: Search(); } void phone::Search{ string phone_number; map<string,vector<Message*>>::iterator iter; cout << "Enter a phone number: "; getline(cin,phone_number); try{ iter = phone_map.find(phone_number); if (iter ==phone_map.end()) { //Incase of a non-existing phone number what do I throw? throw iter; } } catch(/*iter ??? what should the block catch as a value?*/){ cout << "Phone number not found." << endl; } 是否存在,然后我必须检查相应的复选框。即如果列表中有“SUN”,那么我必须检查一下。

3 个答案:

答案 0 :(得分:2)

您可以使用ng-checked

  <span ng-repeat="days in selectDays">
    <input type="checkbox" ng-checked="response.indexOf(days) !== -1" id="{{days}}" ng-model="selectedList[days]" value="{{days | uppercase}}"/>
    <label for="{{days}}">{{days}}</label>
</span>

DEMO

答案 1 :(得分:1)

看看它:

<html>

<head>

    <script src="https://cdnjs.cloudflare.com/ajax/libs/angular.js/1.4.5/angular.min.js"></script> 

</head> 

<body ng-app="myApp" ng-controller="myCtrl"> 

<div id="wrapper" ng-repeat="x in dayList">

<input type="checkbox" ng-checked="findIt(x.name)">{{x.name}}

</div>

<script>
//module declaration
var app = angular.module('myApp',[]);

//controller declaration
app.controller('myCtrl',function($scope){
    $scope.dayList = [{name:'Sun'}, {name:'Mon'}, {name:'Tue'}, {name:'Wed'}, {name:'Thu'}, {name:'Fri'}, {name:'Sat'}];
    $scope.marked = ['Sun','Wed'];

$scope.findIt = function(item){
    if($scope.marked.indexOf(item)!= -1){return true;}
}


});

</script> 

</body> 

</html> 

结果:

enter image description here

希望,这有帮助!

答案 2 :(得分:0)

HTML

<div ng-controller="MyCtrl">
  <span ng-repeat="days in selectDays">
        <input type="checkbox" id="{{days.Day}}"  value="{{days.Day | uppercase}}"  ng-checked="days.IsCheck"/>
        <label for="{{days.Day}}">{{days.Day}}</label>
    </span>
</div>

JS

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

//myApp.directive('myDirective', function() {});
//myApp.factory('myService', function() {});

function MyCtrl($scope, $filter) {
    $scope.selected = ['Sun', 'Wed']
    $scope.selectDays = [{"Day" : 'Sun',"IsCheck" : false},
    {"Day" : 'Mon',"IsCheck" : false}, {"Day" : 'Tue',"IsCheck" : false},
     {"Day" : 'Wed',"IsCheck" : false}]

     angular.forEach($scope.selected,function(obj,i){

             var obj = $filter('filter')($scope.selectDays, { Day: obj })[0];
         if(obj != null)
         {
            obj.IsCheck = true;
        }
     })
}

请找到jsfiddle链接

Demo