AngularJS: how to map objects to HTML attributes

Let me describe what I'm trying to do. I am creating a truly dynamic ng directive to build a table based on an array of data and the provided configuration object. I want to know how to assign attributes dynamically based on an object in scope. Let's say I have an object somewhere in scope:

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

etc. and somewhere in my template

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

and the result will be as follows:

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

How is this possible?

What I tried: Currently, I have managed to create an input for each element in the input array on each line, and I can assign type={{type}} , but the html attributes may vary for each type of input element, and I think that it's nasty to assign attributes in a "hard-coded" way and get stuck here.

Thanks in advance for any feedback!

+6
source share
1 answer

Here you will find 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 name-value pairs to the dynamic-attributes , and the directive will add it for you:

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

In your case, it will be something like this:

 <input dynamic-attributes="inputs.myInput"> 
+5
source

Source: https://habr.com/ru/post/958139/


All Articles