2013-07-04 32 views
0

我需要創建包含從Json對象接收到的數據的外部變量(數組)。這個數據數組將被用來綁定組合框。如何在外部變量中添加值knockoutjs

我曾嘗試: -

var data = [ 
    $.ajax({ 
     type: "POST", 
     url: 'TimeRecord.aspx/ReturnComplexType', 
     data: {}, 
     contentType: "application/json; charset=utf-8", 
     dataType: "json", 
     success: function (arg) { 
      alert('hello Inside new'); 
      for (var i = 0; i < arg.d.length ; i++) { 
       "projectCode"=arg.d[i].ProjectCode 
       //data.push(arg.d[i].ProjectCode) 

      } 

     }, 
     error: function (arg) { 
     } 
    }) 
]; 

HTML代碼:

<td><select id="Select2" data-bind='options: data, value: selectedProject' style="width: 312px"></select> 

我嘗試不同上前值分配給在for循環這個變種變量。但我無法綁定它。請幫助.....

編輯:我的全部其他代碼

function ViewModel() { 
    var self = this; 
    this.CheckIn = ko.observable(); 
    this.CheckOut = ko.observable(); 
    this.Lunch = ko.observable(); 
    this.projectLine = ko.observableArray([new projectsWorked()]); 

    this.TimeForWork = ko.computed(function() { 
     return this.CheckIn() ? this.CheckOut() ? parseFloat(this.Lunch()) ? parseFloat(this.CheckOut()) - parseFloat(this.CheckIn()) - parseFloat(this.Lunch()) : parseFloat(this.CheckOut()) - parseFloat(this.CheckIn()) : 0 : 0; 
    }, this); 

    this.Rest = ko.observable(); 

    this.RemainHour = ko.computed(function() { 
     return self.TimeForWork() ? self.Rest() ? self.WorkOnProject() ? parseFloat(self.TimeForWork()) - parseFloat(self.Rest()) - parseFloat(self.WorkOnProject()) : parseFloat(self.TimeForWork()) - parseFloat(self.Rest()) : parseFloat(self.TimeForWork()) : 0 
    }, this); 

    this.WorkOnProject = ko.observable(); 
    this.grandTotal = ko.observable(); 

    this.AddLine = function() { 
     alert('hello Add'); 
     // alert(this.grandTotal()); 
     this.calcTotal(); 
     this.projectLine.push(new projectsWorked()); 
    }; 

    this.removeLine = function (line) { 
     alert('hello Remove'); 
     self.projectLine.removeLine;  
    }; 
}; 

function projectsWorked() { 
    var self = this; 
    this.projectEnable = ko.observable(false); 
    this.hours = ko.observable(); 
    this.selectedProject = ko.observable(); 

}; 

ko.applyBindings(new ViewModel()); 
+0

調用applybindings在哪裏?你必須將數據源綁定到你的元素 – TGH

+0

@TGH我更新了我的問題 – DevT

回答

1

您要填寫必須是observableArray數據。獲取數據後,您應該設置它。 在您的ViewModel中,您可以將該observableArray和options標記綁定到它。你的代碼應該是這個樣子:

在你的ViewModel一個像這樣的:

optionsData = ko.ObservableArray; 
... 
// later you should make your ajax call and fill optionsData observable 

和您的視圖必須更改綁定到optionsData:

data-bind='options: optionsData 

使全局變量做這些結合不是一個好的解決方案。