2014-02-15 67 views
0

我新的敲除和试图绑定选中的复选框以敲除阵列如何将knockout checked复选框绑定为对象列表?

变种userRoleList = [( “UserTypeId”:1, “UserTypeName”: “系统管理员”) ( “UserTypeId”:2“,UserTypeName “:‘非管理员’) (” UserTypeId“:3‘UserTypeName’:‘检查’) ]

下面是代码在下拉列表并结合选择的用户角色,以敲除可观察到的阵列,以显示用户角色列表,这工作得很好。

<td>           
    <select data-bind='options: $root.userRoleList, optionsText: "UserTypeName", optionsValue: "UserTypeId", optionsCaption: "Select...", value: UserTypeId'></select>                       
</td> 

现在我想显示复选框列表,而不是下拉列表(替换复选框下拉)和m与下面的方式操作的方式,但其值不结合敲除obersvable阵列。

<td>           
    <div class="userRole userRoleEdit" data-bind="foreach: $root.userRoleList">             
    <label data-bind="text: UserTypeName" style="width:50%"></label>                         
    <input type="checkbox" data-bind=" attr: { value: UserTypeId, text:UserTypeName, id: UserTypeId, name: UserTypeName } " />                         
    </div> 
</td> 

你能告诉我我做错了什么吗?

回答

0

首先,创建userRoleList数组时使用了不正确的数组初始化语法。你应该像下面的代码那样重写它。

var viewModel = function() { 
    var self = this; 
    self.selectedRoleList = ko.observableArray([]); 
    self.userRoleList = [{ 
     UserTypeId: 1, 
     UserTypeName: "Admin" 
    }, { 
     UserTypeId: 2, 
     UserTypeName: "NonAdmin" 
    }, { 
     UserTypeId: 3, 
     UserTypeName: "Inspector" 
    }]; 
} 
var vm = new viewModel(); 
ko.applyBindings(vm); 

然后,你应该改变你的HTML:

<div data-bind="foreach: $root.userRoleList"> 
    <label data-bind="text: UserTypeName"></label> 
    <input type="checkbox" data-bind="checked: $root.selectedRoleList, value: UserTypeId" /> 
</div> 

并对其进行测试,如果你想:

<div data-bind="foreach: $root.selectedRoleList"> 
    <label data-bind="text: $data"></label> 
</div> 
相关问题