angularjs: dynamic html dependent on json data

送分小仙女□ 提交于 2019-12-12 21:22:04

问题


I want to show the content of my json model in a dynamic way, depending on the provided json. I use ng-repeat to loop through my data and want to display a html template to fill with data dependent on the encountered data type.

JSON

{
    "elements": [
        {
            "type": "input-text",
            "desc": "Full Name"
        },
        {
            "type": "input-checkbox",
            "desc": "Accept Terms"
        }
    ]
}

This should result in different html code, appropriate filled with the json content.

E.g.

<div><label>Full Name</label> <input type="text"></div>
<div><input type="checkbox"> <label>Accept Terms</label></div>

Right now what I do is to use an angularjs directive to create an element and add the json values to the right spot. e.g. element.html('<div><input type="checkbox"> <label>' + scope.item.desc + '</label></div>') That seems like the jquery way (or worse) to do it although I want to do it the 'right' angularjs way.

How can I use a different HTML template filled with content, dependent on the encountered JSON data?

PS: The above example is a simple one, the encountered data is far more complex than switching the position of the label and input field.


回答1:


All you need to do is set the data on the scope, then use the ng-repeat directive in your HTML to output it:

Controller:

.controller('MyData', function ($scope) {
    $scope.myModel = {
        elements: [ { desc: .. }, .. ]
    };
})

You would be using the $http service or some other appropriate method in this controller to populate myModel with data, but in the end the data needs to end up on the $scope object somehow. Then it's the template's job to display that data:

<div ng-controller="MyData">
    <ul>
        <li ng-repeat="element in myModel.elements">
            {{ element.desc }}
        </li>
    </ul>
</div>



回答2:


A simple solution seems to use ngSwitch with different HTML paths, e.g.:

<div ng-switch="item.type">
    <div ng-switch-when="input-text">
      <div><label>{{item.desc}}</label> <input type="text"></div>
    </div>
    <div ng-switch-when="input-checkbox">
      <div><input type="checkbox"> <label>{{item.desc}}</label></div>
    </div>
    <div ng-switch-default>Unknown item.type: {{item.type}}</div>
</div>

Seems the approach using an angularjs directive (which I took first) may be a good solution for complex scenarios as "Huy Hoang Pham" points out in his blog post: http://onehungrymind.com/angularjs-dynamic-templates/ (thanks!)



来源:https://stackoverflow.com/questions/29295564/angularjs-dynamic-html-dependent-on-json-data

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!