2

My first problem, i don't know make a dynamic template in twig with AngularJs. The purpose of my project, then making a page editor app. So, first of all: - I get a JSON file in the following structure - I started processing the content of JSON file, but I'm getting stuck in processing. Can I ask for a nice solution? Many thanks!

/* Json file */

$scope.form={
'content': 
    [{   
        "name"  : "text_right",
        "img"   : "nope.jpg",
        "text"  : "<span>text text text</span>"           
    },
    {   
        "name"  : "text_left",
        "text"  : "<span>text text text</span>",
        "img"   : "nope.jpg"
    },
    {
        "name"  : "text_both",
        "textL"  : "<span>text text text</span>",
        "textR"  : "<span>text text text</span>"
    },
    {
        "name"  : "special",
        "text"  : "<div>text text text</div>"
    }]
};
/* HTML content */

<div class="col-12" ng-repeat="(key, value) in form.content">
    [[ initTemp(key) ]]
</div>

/* AngularJs */
$scope.initTemp = function($key){
    let html;

    if(form.content[$key].name ==  "text_both"){
        html = textBoth();
    }
    if(form.content[$key].name == "text_left"){
        html = textLeft();
    }
    return $compile(html)($scope);
}
function textBoth($key){
    return `
        <div class="col-6"><input ng-model="form.content.${$key}.textL"></div>
        <div class="col-6"><input ng-model="form.content.${$key}.textR"></div>
    `;
}
function textLeft($key){
    return `
        <div class="col-6"><input ng-model="form.content.${$key}.text"></div>
        <div class="col-6"><input ng-model="form.content.${$key}.img"></div>
    `;
}

1 Answer 1

2

Code that assembles DOM from data is best done in a custom directive:

<div class="col-12" ng-repeat="item in form.content">
     ̶[̶[̶ ̶i̶n̶i̶t̶T̶e̶m̶p̶(̶k̶e̶y̶)̶ ̶]̶]̶
     <custom-directive item="item"></custom-directive>
</div>
app.directive("customDirective", function($compile) {
    return {
        link: postLink,
    };
    function postLink (scope,elem,attrs) {
        var item=scope.$eval(attrs.item);
        var html = `
            <div>
               <img src=${item.img} />
               <!-- ... -->
            </div>
        `;
        var linkfn = $compile(html);
        elem.append(linkfn(scope)); 
    }
})

For more information, see

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.