如何使用angularjs制作动态(可变)内容?

时间:2019-04-25 14:10:01

标签: angularjs twig

我的第一个问题是,我不知道使用AngularJs在树枝中创建动态模板。 我的项目目的,然后制作一个页面编辑器应用程序。 因此,首先: -我得到以下结构的JSON文件 -我开始处理JSON文件的内容,但在处理过程中陷入了困境。 我可以要求一个好的解决方案吗? 非常感谢!

/* 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 个答案:

答案 0 :(得分:2)

从数据组装DOM的代码最好在自定义指令中完成:

<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)); 
    }
})

有关更多信息,请参见