2014-02-15 94 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> 
相關問題