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

1 Answer 1

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.

Sign up to request clarification or add additional context in comments.

2 Comments

Im looking for a dynamic way. something like "include input-{{type}}-template"
@BrandonTilley any thoughts about putting the logic inside of a directive (e.g. 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?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.