4

Note: I'm quite new to angularjs

What is the best solution/practice for problem: I have an array or typed values, for each type there should be different input(template and input validation)?

E.g. and simplified

var vars = [
    {
        type: 'int',
        value: 42,
        min: 0,
        max: 42
    },
    {
        type: 'text',
        value: 'foobar'
    },
]

for 'int' template will be

<input type="range" max="{{max}}" min="{{min}}" value="{{value}}" />

and for 'text'

<textarea>{{value}}</textarea>

In real case there will be quite many inputs with weird interfaces

Viller
  • 540
  • 5
  • 19

1 Answers1

6

An ng-switch (docs) can help you out here; something like this:

<div ng-repeat="item in items">
  <div ng-switch on="item.type">
    <div ng-switch-when="int">
      <input type="range" max="{{item.max}}" min="{{item.min}}"
        ng-model="item.value" />
    </div>

    <div ng-switch-when="text">
      <textarea ng-model="item.value"></textarea>
    </div>
  </div>
</div>

[Update]

Since you mentioned you want to dynamically include a template based on the type, take a look at ng-include (docs) which takes an Angular expression evaluating to a URL:

<div ng-repeat="item in items">
  <div ng-include="'input-' + item.type + '-template.htm'"></div>
</div>

If you don't like the inline string concatenation, you can use a controller method to generate the URL:

<div ng-repeat="item in items">
  <div ng-include="templatePathForItem(item)"></div>
</div>

The example on the ngInclude documentation page is pretty good.

Note that the included template will be given a prototypal child scope of the current scope.

Michelle Tilley
  • 157,729
  • 40
  • 374
  • 311
  • Im looking for a dynamic way. something like "include input-{{type}}-template" – Viller Jul 14 '13 at 04:42
  • @BrandonTilley any thoughts about putting the logic inside of a directive (e.g. http://onehungrymind.com/angularjs-dynamic-templates/)? I guess ng-switch seems a little more modular to me, but it also clutters the dom. I guess it comes down to what you're more comfortable cluttering, dom or directive? – bennlich Nov 12 '13 at 01:20