[SalesForce] Lightning – dynamically creating element and binding it’s attributes

I'm trying out to generate input elements dynamically and wasn't able to bind value attribute.

I getting following error when trying to display component:

enter image description here

testDynamicBinding.cmp

<aura:component description="testDynamicBinding">
    <aura:attribute name="testAttr" type="String" default="Hello World"/>

    <aura:handler name="init" action="{!c.doInit}" value="{!this}"/>

    {!v.body}

</aura:component>

testDynamicBindingController.js

({
    doInit: function(cmp){
        $A.createComponent(
            'ui:outputText',
            {
                value: '{!v.testAttr}'
            },
            function(element, status, errorMessage){
                if (cmp.isValid() && status == 'SUCCESS'){
                    var body = cmp.get('v.body');

                    body.push(element);

                    cmp.set('v.body', element);
                }

            }
        );
    }
})

I don't understand why it gives me this error.

I tried following code (I think it's equivalent to what I try to generate) and that works fine.

<aura:component description="testDynamicBinding">
    <aura:attribute name="testAttr" type="String" default="Hello World"/>

    <aura:set attribute="body">
        <ui:outputText value="{!v.testAttr}"/>
    </aura:set>

</aura:component>

Any piece of advice would be appreciated.

Thanks a lot in advance.

Best Answer

1.In controller u need to get attribute reference value using cmp.getReference("v.testAttr")

2.And set the value to ui:output text

**

({
    doInit: function(cmp){
        var test = cmp.getReference("v.testAttr");
        $A.createComponent(
             'ui:outputText',
            {
                value: test
            },
            function(element, status, errorMessage){
                if (cmp.isValid() && status == 'SUCCESS'){
                    var body = cmp.get('v.body');
                    body.push(element);
                    cmp.set('v.body', element);
                }
            }
        );
    }
})

**

Related Topic