简体   繁体   English

如何在AngularJS中生成DOM元素?

[英]How do I generate DOM elements in AngularJS?

I have a controller with some data with are actions and variable numbers of parameters: 我有一个带有一些数据的控制器,这些数据是动作和可变数量的参数:

$scope.actions = [
 {name : 'rotate', r : '30'},
 {name : 'translate', x : '10', y : '10'},
 {name : 'scale', x : '10', 'y' : 10},
]

So rotate has one parameter, translate and scale have two. 因此旋转有一个参数,平移和缩放有两个参数。 I would like to show a select for each name in actions and then when one is selected show a input type='text' for each parameter that that action has. 我想为操作中的每个name显示一个select ,然后在select一个name时为该操作具有的每个参数显示input type='text' What is the easiest way to do this in Angular? 在Angular中最简单的方法是什么?

The easiest way that i can think of is to use templates with ng-include 我能想到的最简单的方法是将模板与ng-include一起使用

Create 3 templates one for each dropdown value, such as 为每个下拉值创建3个模板,例如

<script type="text/ng-template"  id="rotate">
<div>Angle</div> <input type='text' ng-model='r'/>
</script>

The template name should match the selected element name 模板名称应与所选元素名称匹配

Define a ng-include like 定义一个ng-include像

<ng-include src ="selectedAction.name"></ng-include>

In your controller code create a selectedAction variable on the scope, and change it whenever the selection changes. 在您的控制器代码中,在作用域上创建一个selectedAction变量,并在选择更改时对其进行更改。

Whenever selectedAction property changes, this would cause a appropriate template to get loaded based on the action selected. 每当selectedAction属性更改时,这将导致根据所选操作加载适当的模板。

If the unique set of name values is relatively small, you might be able to get away with using ng-switch : 如果唯一的一组name值相对较小,则可以使用ng-switch摆脱ng-switch

<select ng-model="selectedAction" ng-options="action.name for action in actions">
  <option value="">Select an Action</option>
</select>

<div ng-switch="selectedAction.name">
  <div ng-switch-when="rotate">
    <div><label>r: </label><input ng-model="selectedAction.r"></div>
  </div>

  <div ng-switch-when="translate">
    <div><label>x: </label><input ng-model="selectedAction.x"></div>
    <div><label>y: </label><input ng-model="selectedAction.y"></div>
  </div>

  <div ng-switch-when="scale">
    <div><label>x: </label><input ng-model="selectedAction.x"></div>
    <div><label>y: </label><input ng-model="selectedAction.y"></div>
  </div>
</div>

JSFiddle example JSFiddle示例

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM