AngularJS multi select flags are stored in a comma separated String

I want to get a comma-separated string from selected check-box elements in angularJS. At the same time, when the comma string is retrieved from the database, I want the checkboxes 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 solved the problem very simply, this 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 this does not help when I have a lot of similar items. Can someone help me create a directive or extension so that I can reuse them often. Postscript I don't want an array of objects, but just comma-separated string elements.

+6
source share
1 answer

If you use "indexOf", you will get many garbage items that include the text that you want to find.

So, I think this is the best way to get a more accurate value.

 if (new RegExp("\\b"+"Car"+"\\b").test(str)) { $scope.Drawings.CarMDrawings = true; } var str="test ,Car ,test"; //true var str="test, Car, test"; //true var str="test Cartest"; //false var str="testCar test"; //false 

This may be a very late answer, but I hope this is right for your intentions,

and useful for other people who will look at this. :)

0
source

Source: https://habr.com/ru/post/989508/


All Articles