我正在使用ui-grid和AngularJS(以及後端的MySQL)作爲項目。我有一張從MySQL數據庫獲取數據的表格。它的行(或單元格)是可編輯的(如在ui-grid網站上的example中所述)。表格的一列有下拉菜單。如該示例中所述,Dropdown與硬編碼數據完美協作。我想從數據庫填充它,但每次嘗試時都會顯示空的下拉列表。無法將動態數據加載到UI網格下拉列表中
從數據庫獲取數據是通過注入控制器的服務完成的,意圖運行從數據庫獲取數據的代碼(即$ http.get('/ some/route')),以便我們擁有所有在頁面加載之前或頁面加載時手錶中的行和下拉列表的數據。
但是打印時獲取下拉數據的變量(sitesD)顯示它未定義。
這裏是控制器:
angular.module('WorkersCtrl', []).controller('WorkersController', function($scope, $http, serverData) {
$scope.gridOptions = {enableHorizontalScrollbar: 1};
/* getting rows from databse by using "serverData" custom service */
serverData.getData().then(function(response) {
$scope.gridOptions.data = response.data[0];
$scope.sitesData = response.data[1];
});
var sitesD = $scope.sitesData;
$scope.gridOptions.columnDefs = [
{ field: 'first_name', width:150, enableCellEdit: true},
{ field: 'last_name', width:150},
{ field: 'father_first_name', width:150},
{ field: 'father_last_name', width:150},
{ field: 'mother_first_name', width:150},
{ field: 'mother_last_name', width:150},
{ field: 'sex', width:50, editableCellTemplate: 'ui-grid/dropdownEditor',
editDropdownValueLabel: 'gender', editDropdownOptionsArray: [
{ id: 'M', gender: 'Male' },
{ id: 'F', gender: 'Female' }]},
{ field: 'address', width:250},
{ field: 'phone', width:100, type: 'number'},
{ field: 'date_of_birth', width:150, type: 'date', cellFilter: 'date:"yyyy-MM-dd"'},
{ field: 'post_code', displayName: 'Post', width:50},
{ field: 'joining_date', width:150, type: 'date', cellFilter: 'date:"yyyy-MM-dd"'},
{ field: 'rate', width:50, type: 'number'},
{ field: 'site_name', width:150, editableCellTemplate: 'ui-grid/dropdownEditor',
editDropdownIdLabel:'site_id', editDropdownValueLabel: 'site_name', editDropdownOptionsArray: sitesD },
];
alert(sitesD); //checking the variable value: it shows undefined.
$scope.gridOptions.onRegisterApi = function(gridApi){
$scope.gridApi = gridApi;
};
$scope.addData = function() {
$scope.gridOptions.data.push({
'first_name': '',
'last_name': '',
'father_first_name': '',
'father_last_name': '',
'mother_first_name': '',
'mother_last_name': '',
'sex': '',
'address': '',
'phone': '',
'date_of_birth': '',
'post_code': '',
'joining_date': '',
'rate': '',
'site_name': ''
});
};
});
服務守則如下:
angular.module('GeekService', []).factory('serverData', ['$http', function($http) {
return {
getData: function() {
return $http.get('/workers')
}
}
}]);
我的理解是可變的在頁面加載後獲取值,因此editDropdownOptionsArray
對於下拉菜單沒有任何價值。
所有這些都是我在尋找解決方案時所做的假設,但尚未成熟。請幫幫我。我覺得我甚至不明白問題在哪裏。
如果需要,隨時提供進一步的信息。 PS:在寫我發現的問題時,我的Angular和ui-grid之間存在版本不兼容問題。 ui-grid 3.x與Angular 1.4.x兼容,但我使用ui-grid 3.x和Angular 1.5.5。這可能是原因嗎?
使用'$ scope.apply();' –
我試了一下如下: 'serverData。 getData()。then(function(response){scope = $ scope。$ apply(function(){ $ scope.gridOptions.data = response.data [0]; $ scope.sitesData = response.data [1]; }); }); ' 它引發此錯誤:錯誤:$ rootScope:inprog 已執行操作 – harman052