Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Dynamic variable name directive attribute

I have a my-edit directive that has a value attribute expecting a scope variable to bind to.

<my-edit value="myVar"></my-edit>

is there any way to do something like this:

<my-edit value="{{varName}}"></my-edit>

where varName = "myVar"

I want to nest this directive in "my-listbox" directive that has a "text-field" attribute

<my-listbox ng-model="myList" text-field="itemProp"></my-listbox>

So I was trying use a template like:

<div>
    <ul>
        <li ng-repeat="item in items">
            <my-edit value="item.{{textField}}"></my-edit>          
        </li>
    </ul>
</div>

But obviously it doesn't work

I guess using a text binding is also not the solution.

Is a dynamic generated template for "my-listbox" the way to go here?

I tried that in the compile function but the didn't work that well because of the nested neRepeat directive. Should it by done using $compile in link function?

Thanks

like image 286
RuiFortes Avatar asked Jun 18 '26 04:06

RuiFortes


1 Answers

This is something pretty cool about angular, it evaluated the string that you pass to the directive. This means that you can actually just do value="item[textField]" and that will work.

For instance if you had a controller with data like this:

$scope.data = {
    test: 'test_val',
    other: 'other_val'
};
$scope.val = 'test';

You could just pass it like this to your directive:

<directive value="data[val]"></directive>

That is set up like this:

scope: {
    value: '='
},

And the isolate scope will have scope.value = 'test_val' and will update to 'other_val' just by changing the original controller val to 'other'

I made a fiddle where this is set up for you to play with.

Hope this helps!

like image 190
hassassin Avatar answered Jun 20 '26 19:06

hassassin



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!