nlr_p nlr_p - 17 days ago 5
AngularJS Question

How to check the check boxes based on the values stored in db(Angularjs)

I am able to insert values to db according to checked but i am failed to check the values while fetching from db ..can any one provide me some help.Thanks.

My template,

<div class="btn-group col-xs-4 nopadding" ng-repeat="type in vm.bussinesstypeoptions" data-toggle="buttons">
<label class="col-xs-12 btn btn-white" ng-click="toggleSelection(type)" ng-class="{'active': type == checkvalue.name }">
<input type="checkbox" name="selectbox" value="type" ng-checked="vm.selection.indexOf(checkvalue.name) > -1" required> {{type}}
</label>
</div>


My values in stored in db as,

"business_type" : [
"Education Consultant",
"Guardianship",
"Hotel/Home-Stay"
],

Answer

First of all, Instead of value, use ng-model, when using the angular way.

then make the ng-checked to the value of that ng-model.

ng-model="type" and ng-checked="type"

Here is the solved snippet:

var app = angular.module('myApp', []);
app.controller('myCtrl', function($scope) {

$scope.bussinesstypeoptions = ['Education Consultant', 'Ticket/Travel', 'Hotel/Home-Stay', 'Guardianship', 'Visa/Solicitors', 'Others']; 

$scope.object = {}
$scope.business_type = [ 
    "Education Consultant", 
    "Guardianship", 
    "Hotel/Home-Stay"
]


for(i = 0;i < $scope.business_type.length; i++)
{

$scope.object[$scope.business_type[i]] = true;
 console.log($scope.object)
  
}
});
<!DOCTYPE html>
<html>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.4.8/angular.min.js"></script>
<body>

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

<div class="btn-group col-xs-4 nopadding"  ng-repeat="type in bussinesstypeoptions" data-toggle="buttons">
   <label class="col-xs-12 btn btn-white" ng-click="toggleSelection(type)" ng-class="{'active': object.type}">
 <input type="checkbox" name="selectbox" ng-checked="object[type]" required ng-model="type"> {{type}}
  </label>
</div>

</div>

</body>
</html>

Here is a fiddle of it

Comments