Sign up ×
Stack Overflow is a community of 4.7 million programmers, just like you, helping each other. Join them; it only takes a minute:

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!

share|improve this question

1 Answer 1

up vote 4 down vote accepted

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">
share|improve this answer
    
I will try that right now! Thank you. – kuncajs Nov 15 '13 at 11:55
    
Perfect, exactly what I needed – kuncajs Nov 15 '13 at 12:04

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.