Repeaters, Switches, and Sections, Oh My
-
21-12-2019 - |
Question
I'm trying to make a form designer/builder with webapi and angularjs. I'm passing a number of fields given a form id. One of the key value pairs that is passed along is what section the field should be in. The sections are essentially a div.well that with h5{section} as the section header. The problem that I want to have 2-3 sections containing several fields but I can't seem to figure out the right way build my partial. Here is a link to a JSFiddle I was working on
<link href="//netdna.bootstrapcdn.com/bootstrap/2.3.2/css/bootstrap.min.css" rel="stylesheet">
<div ng-app="myApp">
<div ng-controller="FormCtrl">
<div class="well" style='overflow: hidden'>
<div ng-repeat="formfield in form.FormsFields | filter:q">
<div ng-switch on="formfield.Field.fieldType">
<div ng-switch-when="Txt" class="span{{formfield.spanSize}}" style="margin-left: 5px; ">
<label for="" class="label label-info">{{formfield.Field.label}}</label>
<input type="text" class="input-block-level" section="{{formfield.section}}" name="" id="test">
</div>
<div ng-switch-when="Are" style="margin-left: 5px; ">
<br>
<div>
<label for="" class="label label-info">{{formfield.Field.label}}</label>
<textarea class="input-block-level" name="" section="{{formfield.section}}" id="test"></textarea>
</div>
</div>
<h1 ng-switch-default>Error</h1>
</div>
</div>
</div>
</div>
Solution
You can use something like underscore to first group the fields into sections and then map them into something easily bindable in the UI.
$scope.sections = groupBySection(data);
function groupBySection(data) {
var grouped = _.groupBy(data.FormsFields, 'section');
return _.map(grouped, function(val, key){
return { name: key, fields: val };
});
};
And of course a jsFiddle showing it all working.
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow