Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

AngularJS: How to map object to HTML attributes

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>

and the result would be:

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

Is this somehow possible?

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.

Thanks in advance for any feedback!

like image 659
kuncajs Avatar asked Nov 15 '13 11:11

kuncajs


1 Answers

Here's a plunk for you:

.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">
like image 135
package Avatar answered Sep 29 '22 08:09

package