我需要將$http.get
返回的數據存儲在$scope
變量中,以供我的ui-grid
控件使用。
我確定我錯過了一些非常簡單的事情,但我無法找出什麼。這裏是我的代碼:
app.controller('AdminUsersGridCtrl', function ($scope, $http, uiGridConstants) {
$http.get('/api/admin/user')
.success(function (response, $scope) {
$scope.myData = response;
})
.error(function (error) {
console.log(error);
});
console.log($scope.myData);
$scope.gridOptions = {
data: 'myData',
enableFiltering: true,
columnDefs: [
{ field: 'firstName' },
{ field: 'lastName' },
{ field: 'jobTitle'},
{
field: 'email',
filter: {
condition: uiGridConstants.filter.ENDS_WITH,
placeholder: 'ends with'
}
},
{
field: 'phone',
filter: {
condition: function(searchTerm, cellValue) {
var strippedValue = (cellValue + '').replace(/[^\d]/g, '');
return strippedValue.indexOf(searchTerm) >= 0;
}
}
},
]
};
});
我的控制檯成功打印undefined
。如何訪問$http.get success
功能中的原始$scope
?
您可以訪問它,只是因爲AJAX =異步,您的代碼的其餘部分在「成功」之前執行。當您的控制檯記錄myData範圍變量時,將代碼移動到回調 – tymeJV
,確實是** undefined **,因爲您仍在執行**異步http獲取請求**。如果你需要將「myData」綁定到gridOptions,並且希望100%確定它將被正確加載並且沒有錯誤,請在**。success **回調中解析代碼,或者創建一個'Promise'並解析它一旦http請求完成。 – briosheje