Angularjs动态指令 [英] Angularjs dynamic directives

查看:98
本文介绍了Angularjs动态指令的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

注:我是很新的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)?

例如。并简化了

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

有关'诠释'模板将

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

和对文

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

在实际情况下,会有相当多的输入怪异接口

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

推荐答案

这是 NG-开关文档)可以在这里帮助你;是这样的:

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>

[更新]

既然你提到要动态包括基于类型的模板,看看 NG-包括文档),它接受一个角前pression评估一个网址:

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>

ngInclude 文档页面上的例子是pretty不错。

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.

这篇关于Angularjs动态指令的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆