내 Angular 앱에는 baseController에 자체 범위를 삽입하여 정의 된 함수에 액세스 할 수 있는 baseController.js
클래스와 클래스 exampleController.js
가 있습니다 baseController
. 이를 통해 모든 컨트롤러간에 기능을 공유 할 수 있습니다.
에서 getDataFromUrl()
함수를 호출하려는 경우를 제외하고는 작동 exampleController
합니다. 디버깅하는 동안 getDataFromUrl()
호출 되는 것을 볼 수 .success()
있으며 $http.get()
호출 기능으로 들어갑니다 . 그 시점에서 나는 그것이 data
deserialized JSON 객체 (이 경우 객체의 배열)임을 알 수 있지만 코드가 마침내 exampleController
의 initArray()
함수로 돌아올 data
때 궁극적으로 수신하는 것은 더 이상 deserialized 객체가 아니지만 원시 HTTP 응답 데이터.
baseController.js :
// Data retrieval function for all derived controllers
$scope.getDataFromUrl = function (url) {
return $http.get(url)
.success(function (data) {
return data;
})
.error(function () {
return null;
});
};
exampleController.js :
appModule.controller('exampleController', [
'$scope', '$controller', '$http', '$window', '$location', '$timeout',
function ($scope, $controller, $http, $window, $location, $timeout) {
var base = $controller('baseController', { $scope: $scope });
// Initiate an array of data
var initArray = function (data) {
$scope.sortedArray = sortDataByDate(data);
};
// Calling function in scope defined by base controller class
$scope.getDataFromUrl('resources/data').then(function (data) {
initArray(data);
});
}]);
HTTP 응답으로 data
돌아 오는 이유는 무엇 exampleController
입니까? 역 직렬화 된 JSON으로 유지하고 싶습니다!
그것을 알아 냈고, .then()
결과로 발생하지 않기 때문에 원시 응답 데이터를 얻고 있었기 때문에 .success()
자식 컨트롤러에 도착하는 데이터는 처음부터 역 직렬화되지 않았습니다. 다음은 올바른 코드입니다.
baseController.js :
// Data retrieval function for all derived controllers
$scope.getDataFromUrl = function (url, successFunction) {
$http.get(url)
.success(function (data) {
successFunction(data);
})
.error(function () {
return null; // Or whatever you want to return
});
};
exampleController.js :
appModule.controller('exampleController', [
'$scope', '$controller', '$http', '$window', '$location', '$timeout',
function ($scope, $controller, $http, $window, $location, $timeout) {
var base = $controller('baseController', { $scope: $scope });
// Initiate an array of data
var initArray = function (data) {
$scope.sortedArray = sortDataByDate(data);
};
// Calling function in scope defined by base controller class
$scope.getDataFromUrl('resources/data', function (data) {
initArray(data);
});
}]);
이 기사는 인터넷에서 수집됩니다. 재 인쇄 할 때 출처를 알려주십시오.
침해가 발생한 경우 연락 주시기 바랍니다[email protected] 삭제
몇 마디 만하겠습니다