AngularJS:如何映射对象的HTML属性 [英] AngularJS: How to map object to HTML attributes

查看:302
本文介绍了AngularJS:如何映射对象的HTML属性的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

让我描述我所试图做的。
我建立一个真正的动态NG指令根据提供的数据阵列和配置对象来建表。我想知道的是如何根据范围对象上动态地分配属性。比方说,我在这样的范围有一个对象的话:

let me describe what I am trying to do. I am building a really dynamic ng directive to build table based on data array and config object provided. What I want to know is how to assign attributes dynamically based on an object in scope. Let's say I have an object somewhere in scope like:

$scope.inputs.myInput = {
    type : "number",
    size : 3,
    min : 0,
    ...
}

等等某处在我的模板是

and so on and somewhere in my template is

<tr><td>other stuff</td><td><input {{assign the attributes somehow}} /></td></tr>

和的结果将是:

<tr><td>other stuff</td><td><input type='number' size='3' min='0' ... /></td></tr>

这是某种程度上可能吗?

Is this somehow possible?

我试过:目前,我管理的每行中创建输入数组每个项目的投入,我可以通过的类型指定类型= {{类型}} 但HTML属性不同,可以为每种类型的输入元素,我认为这将是坏坏地分配属性元素硬$ C $光盘的方式,得到了困在这里。

What I tried: Currently, I managed to create an input for each item in input array in every row and I can assign a type by type={{type}} but html attributes can differ for each type of input element and I think it would be nasty to assign attributes to element "hard-coded" way and got stuck here.

先谢谢您的任何反馈!

推荐答案

这儿有你一个普拉克:

.directive('dynamicAttributes', function($parse){
  return function($scope, $element, $attrs) {
    var attrs = $parse($attrs.dynamicAttributes)($scope);
    for (var attrName in attrs) {
      $attrs.$set(attrName, attrs[attrName]);
    }
  }
})

只是通过您的属性名称 - 值对动态属性的对象属性,该指令将其添加为您:

Just pass your object of attribute name-value pairs to the dynamic-attributes attribute and the directive will add it for you:

dynamic-attributes="{style:'background: red;height:200px;', class: 'red'}"

在你的情况下,它会是这样的:

In your case it would be something like that:

<input dynamic-attributes="inputs.myInput">

这篇关于AngularJS:如何映射对象的HTML属性的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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