车把选择框填充

时间:2016-11-15 07:14:01

标签: javascript json node.js handlebars.js

我的HTML代码,

我希望在每个用户名的选择框旁边选择每个用户角色

在每个角色循环内部我无法访问父用户节点的角色, 是否可以将用户节点的角色id与角色节点roleid进行比较,当它相等时,将选择该选项

<table>
<tr>
    <p>peter is employee</p>
  <p>john is admin</p>
  <p>michel is manager</p>
</tr>
{{#user}}
<tr>
    <td>
        <input type="text" value="{{name}}">
    </td>

    <td>
        <select>
            {{#each ../roles}}
            <option value="{{roleid}}">{{value}}</option>
            {{/each}}
        </select>
    </td>
</tr>
{{/user}}

这可能是Json

var data = {
"user": [
    { "name": "peter", "role": 1 },
    { "name": "john", "role": 2 },
    { "name": "michel", "role": 3 }
],
"roles": [
    { "roleid": 1, "value":"manager"},
    { "roleid": 2, "value":"employee"},
    { "roleid": 3, "value":"admin"}
]
};

小提琴网址https://jsfiddle.net/Manu_S/egbwbfav/2/

感谢

1 个答案:

答案 0 :(得分:1)

您可以访问父节点值并在选择框中进行比较。

请按照Jsfiddle工作

https://jsfiddle.net/gsubbarao/nz0bc0pq/

<script id="t" type="text/x-handlebars">
<table>
<tr>
    <p>peter is employee</p>

  <p>john is admin</p>
  <p>michel is manager</p>
</tr>
<tr>
<td>&nbsp;</td><td></td><td></td>
</tr>
{{#user}}
<tr>
    <td>
        <input type="text" value="{{name}}">
    </td>

    <td>
        <select>
            {{#each ../roles}}
            <option value="{{roleid}}"
            {{#ifCond  ../role roleid}}
            selected
            {{/ifCond}}
            >
            {{value}}
            </option>

            {{/each}}
        </select>
    </td>
</tr>
{{/user}}

</script>

    var data = {
    "user": [
        { "name": "peter", "role": 2 },
        { "name": "john", "role": 3 },
        { "name": "michel", "role": 1 }
    ],
    "roles": [
        { "roleid": 1, "value":"manager"},
        { "roleid": 2, "value":"employee"},
        { "roleid": 3, "value":"admin"}
    ]
};
Handlebars.registerHelper('ifCond', function(v1, v2, options) {
  if(v1 === v2) {
    return options.fn(this);
  }
  return options.inverse(this);
});
var t = Handlebars.compile($('#t').html());
$('body').append(t(data));