Issue
I shows amenities checkbox options as ng-repeat of a json array and i stored into database as comma separated ids like "1,3,7" as a single string but when i need to edit amenities checkbox i am unable to show existing options as checked because i get existing value from db as 1,3,7 as single string how i will check this string with options in the ng-repeat ?
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.6.9/angular.min.js"></script>
<script>
var app = angular.module('myApp', []);
app.controller('myCtrl', function($scope) {
$scope.amenities=[{id:1,value:"Wifi"},
{id:2,value:"AC"},
{id:3,value:"Creditcard"},
{id:4,value:"24x7"},
{id:5,value:"Parking"},
{id:6,value:"Free delivery"},
{id:7,value:"No Smoking"}
];
//For example assume that this is existing amenities from database
$scope.existamenities="1,3,7";
});
</script>
<htmL>
<div ng-app="myApp" ng-controller="myCtrl">
<div ng-repeat="amn in amenities">
<label>{{amn.value}}
<input type="checkbox" name="amenities" ng-value="amn.id">
</label>
</div>
</div>
</htmL>
Solution
I believe for them to be checked you need to set the ng-model
to true or false. Simply create another array and populate it accordingly.
You have an option to append the existing array with new properties that will hold true/false values, or create a new array that was mapped from the original one. Then simply switch default false
values to true
if their ID is listed, which you can get by splitting the string.
Here is a small demo:
var app = angular.module('myApp', []);
app.controller('myCtrl', function($scope) {
$scope.amenities = [
{id:1,value:"Wifi"},
{id:2,value:"AC"},
{id:3,value:"Creditcard"},
{id:4,value:"24x7"},
{id:5,value:"Parking"},
{id:6,value:"Free delivery"},
{id:7,value:"No Smoking"}
];
//For example assume that this is existing amenities from database
$scope.existamenities = "1,3,7";
var a = $scope.existamenities.split(",").map(x => Number(x))
var b = $scope.amenities.map((x) => {
return {
"id": x.id,
"val": false
}
})
for (var i = 0; i < b.length; i++) {
for (var j = 0; j < a.length; j++) {
if (b[i].id == a[j]) {
b[i].val = true
}
}
}
$scope.model = b;
});
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.6.9/angular.min.js"></script>
<div ng-app="myApp" ng-controller="myCtrl">
<div ng-repeat="amn in amenities">
<label>{{amn.value}}
<input type="checkbox" name="amenities" ng-model="model[$index].val" ng-value="amn.id">
</label>
</div>
Answered By - Aleksey Solovey
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.