2016-12-09 159 views
1

在我的web應用程序中存在複選框列表。我需要的是,從後臺獲取數據存在的列表,基於這些數據我想自動檢查複選框。如果它混淆下面是我的代碼。如何根據angularjs中的數據自動選擇複選框?

HTML

<span ng-repeat="days in selectDays"> 
     <input type="checkbox" id="{{days}}" ng-model="selectedList[days]" value="{{days | uppercase}}"/> 
     <label for="{{days}}">{{days}}</label> 
    </span> 

控制器

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

從後端我得到以下數據正在響應

["SUN", "MON"]; 

下面我分享我的網頁快照。 enter image description here

我的需求是檢查響應數據與$scope.selectDays如果存在,那麼我必須檢查各自的複選框。即如果列表中有「SUN」,那麼我必須檢查它。

+0

根據我的理解提供答案,讓我知道任何你需要的東西! –

回答

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

您可以使用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

+0

KISS!好的解決方案 – lin

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

相關問題