I want to get comma separated string from selected check-box items in angularJS. At the same time, when comma separated string is retrived from database, I want check-boxes to be checked accordingly.
<div class="col-md-5">
<input type="checkbox" ng-model="Drawings.CarMDrawings" ng-change="Update(Drawings)"> Car
<br />
<input type="checkbox" ng-model="Drawings.SignalMDrawings" ng-change="Update(Drawings)"> Signal
<br />
<input type="checkbox" ng-model="Drawings.DoorMDawings" ng-change="Update(Drawings)"> Door
<br />
</div>
I have solved the problem in very simplistic way is Plunker http://plnkr.co/edit/YYd5bN5Chmyjt6gSH1Bw?p=preview
$scope.Update = function(Drawings) {
var str = "";
if (Drawings.CarMDrawings) {
str = "Car";
}
if (Drawings.SignalMDrawings) {
str = str + ",Signal";
}
if (Drawings.DoorMDawings) {
str = str + ",Door";
}
if (str.charAt(0) === ',') {
str = str.substr(1);
}
$scope.data = str;
}
$scope.revUpdate = function(data) {
var str = data;
$scope.Drawings = {};
if (str.indexOf('Car') != -1) {
$scope.Drawings.CarMDrawings = true;
}
if (str.indexOf('Signal') != -1) {
$scope.Drawings.SignalMDrawings = true;
}
if (str.indexOf('Door') != -1) {
$scope.Drawings.DoorMDawings = true;
}
}
But it is not helpful when I have many similar items. Could any one help me building a directive or extension so that I could reuse them frequently. P.S. I don't want array of objects but simple comma separated string items.
If you use 'indexOf', you'll get many garbage items those include text what you want to find.
So I think this is the most nearest way to get more precise value.
Maybe this is very late answer but I hope this is right for your intent,
and helpful for other people who'll look this. :)