jsviews如何使列表元素被选中

jsviews how to make list element selected

我正在尝试为用户显示项目列表。在 select 列表中 'key' 用户 属性 的当前值应该被 selected,但这不起作用。

这是我的代码片段:

<script id="usersTmpl" type="text/x-jsrender">
{^{for users}}
    {^{for permissions}}
        <select data-link="key">
            {^{for ~projects(app)}}
            <option data-link="{:key} selected{:key === {{>#parent.data.key}}}"></option>
            {{/for}}    
        </select>
    {{/for}}
{{/for}}    
</script>
function getProjects(application) {
    var keys = [];
    permissions.projects.forEach( function (project)
        {
            if(project.application == application) {
                keys.push(project);
            }
        });
  return keys;
}

var usersTemplate = $.templates("#usersTmpl");

var users = [
    {
        username: "first",
        displayName: "First User",
        email: "mymail@localhost",
        permissions: [
            {
                app: "APP1",
                key: "PRJ2",
                name: "admin"
            },
            {
                app: "APP1",
                key: "PRJ",
                name: "view"
            },
            {
                app: "APP2",
                key: "CFL2",
                name: "view"
            }
        ]
    }
]
var projects = [{application: "APP1", name: "Project", key: "PRJ", lead: "leaduser"}, {application: "APP1", name: "Project2", key: "PRJ2", lead: "leaduser2"},
        {application: "APP2", name: "Name1", key: "CFL1", lead: "leaduser"}, {application: "APP2", name: "Name2", key: "CFL2", lead: "leaduser"}]

var permissions = {
    applications: ["APP1", "APP2", "APP3"],
    projects: projects,
    users: users,


}

$.views.helpers({projects: getProjects});
usersTemplate.link("#usersList", permissions);

http://jsfiddle.net/er2f1rw3/1/

谁能帮我理解为什么这不起作用?

您 data-link 在 <option> 上的表达不正确。您需要:

<option data-link="{:key} selected{:key === #parent.parent.data.key}"></option>

请注意,您需要升级两个 parents。 (因为使用 {{for}} 进行迭代,所以数组有一个视图,其中包含每个项目的 child 视图。)

另一种方法是传入外部 key,如下所示:

{^{for ~projects(app) ~outerkey=key}}
    <option data-link="{:key} selected{:key === ~outerkey}"></option>
{{/for}}    

这是您的 jsfiddle 的更新版本,使用了这两种方法。

http://jsfiddle.net/er2f1rw3/2/

更改 drop-down,其他相应的 drop-down 也通过 two-way 绑定进行更新。