Dynamic Angularjs Directives

Note: I'm pretty new to angularjs

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

eg. and simplified

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

for the template 'int' will be

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

and for 'text'

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

In the real case, there will be quite a few inputs with strange interfaces

+4
source share
1 answer

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

 <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 that you want to dynamically include a template based on this type, look at ng-include ( docs ), which accepts an Angular expression evaluating the URL:

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

If you don't like the built-in string concatenation, you can use the controller method to create the URL:

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

The example on the ngInclude documentation ngInclude pretty good.

Note that the included template will be provided with a prototype child region of the current region.

+6
source

Source: https://habr.com/ru/post/1491297/


All Articles