Angularjs dynamic directives

angularjs, javascript

Solution

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.

Problem

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

Original source