lazarov lazarov - 11 months ago 65
AngularJS Question

Create html elements in ngRepeat depending on object properties

I have an array of objects that have two fileds for example :

var array = [{type:"range", group:"group1"}, {type:"boolean", group:"group1"},
{type:"input", group:"group3"}... ]

Now in HTML by iterating through the array I want to create a div for every different GROUP and put the all elements with that group inside. But by putting I mean creating Inputs or Radiobuttons or Dropdowns depending on the TYPE of the element.

Now I have done this using AngularJS and mostly JS by appending objects to existing ones and so on. But I want to reduce as much as possible the usage of js because I am having issue with calling a function after the HTML is loaded (Call function after HTML is loaded AngularJS).

So I will be thankfull if someone give me an advice how this should look like mostly in html. I imagine something like this :

<div ng-repeat="object in array track by $index">
//if div exists add to existing one (check maybe with js function ?)
// if object.type is ... add ...
// else if objec.type is ... add ...
//else not exists create div with id for example
// if object.type is ... add ...
// else if object.type is ... add ...


This should work for your case:

<div ng-repeat="(key, value) in array | groupBy: 'group'">
  Group: {{key}}
    <div ng-repeat="object in value">
      <div ng-switch on="object.type">
        <div ng-switch-when="range">Range block</div>
        <div ng-switch-when="boolean">Boolean block</div>
        <div ng-switch-when="input">Input block</div>

First looping groups elements, second will work with an elements in a group