2013-07-09 34 views
0

誰能告訴我如何我可以預先從基於從ajax調用回傳的對象的下拉列表中選擇一個值。我一直在經歷淘汰賽的教程,並一直在嘗試一些事情。它從不根據員工的職位對象在下拉列表中選擇正確的值。下面是我的代碼,這裏是一個鏈接到我的小提琴預選使用淘汰賽在選擇框中的值

http://jsfiddle.net/ricobano/HcRVH/1/

<div data-bind="foreach: employees"> 
    <div> 
     <label>Full Name</label> 
     <input data-bind="value: fullName" /> 
     <label>Position</label> 
     <select id="slTest" data-bind="options: $root.Positions, value:position, optionsText:'name'"></select> 
     <label>Salary:</label><span data-bind="text: position().salary"></span> 
    </div> 
</div> 

function Employee(fullname, position) { 
    var self = this; 
    self.fullName = ko.observable(fullname); 
    self.position = ko.observable(position); 
} 

function Position(id, name, salary) { 
    var self = this; 
    self.id = ko.observable(id); 
    self.name = ko.observable(name); 
    self.salary = ko.observable(salary); 
} 

function EmployeeVM() { 
    var self = this; 
    self.employees = ko.observableArray(); 

    self.Positions = [ 
    new Position(1, "No position", "0"), 
    new Position(3, "Web Developer", "15100"), 
    new Position(2, "Manager", "30000")]; 

    var data = { 
     json: $.toJSON([{ 
      "fullName": "Richard Banks", 
       "position": { 
        "id": 2, 
       "name": "Manager", 
        "salary": "30000" 
      } 
     }, { 
      "fullName": "Dave Grohl", 
       "position": { 
        "id": 3, 
       "name": "Web Developer", 
        "salary": "15100" 
      } 
     }, { 
      "fullName": "bobby rahul", 
       "position": { 
        "id": 3, 
       "name": "Web Developer", 
        "salary": "15100" 
      } 
     }]) 
    }; 

    $.ajax({ 
     url: "/echo/json/", 
     data: data, 
     type: "POST", 
     success: function (response) { 
      $.each(response, function (i, item) { 
       var e = new Employee(item.fullName, new Position(item.position.id, item.position.name, item.position.salary)); 
       self.employees.push(e); 
      }); 

      //alert($("#slTest").html()); 
     } 
    }); 
} 

ko.applyBindings(new EmployeeVM()); 

回答

0

淘汰賽上的對象options綁定工作,在默認情況下,這是你如何使用它。問題是,positions數組與employee具有不同的position對象,即使它們具有相同的值,因爲您正在爲每個員工製作新的position對象。

您將不得不選擇如何存儲位置。

可以使用optionsValue綁定映射爲員工位置的id,如this fiddle does

<select id="slTest" data-bind="options: $root.Positions, value:position, optionsText:'name', optionsValue: 'id'"></select> 
--- 
$.each(response, function (i, item) { 
       var e = new Employee(item.fullName, item.position.id); 
       self.employees.push(e); 
      }); 

,或者你將不得不ideach循環來查找position,並把它傳遞給員工,如this fiddle那樣

$.each(response, function (i, item) { 
       var position = ko.utils.arrayFirst(self.Positions, function(p) { 
        return p.id() == item.position.id; 
       }); 
       var e = new Employee(item.fullName, position); 
       self.employees.push(e); 
      });