gpt4 book ai didi

javascript - 将参数传递给 angularjs/javascript 中的命名回调函数的问题

转载 作者:行者123 更新时间:2023-11-30 07:15:42 30 4
gpt4 key购买 nike

我想分解angularjs $http success callback function这样我就不用两个(或N个)anonymous callback functions一个命名的回调函数

这是两个 Controller :

function CreateCurriculumCtrl($scope, $http, $location, select2Options){

$scope.curriculumInfo = {};
$scope.curriculumInfo.statusOK = true;
$scope.select2Options = select2Options;

$scope.saveCurriculum = function(){
$http.post('bignibou/curriculum/new', $scope.curriculumInfo).success(function(curriculumInfo) {
if(curriculumInfo.statusOK == true){
$scope.curriculumInfo.statusOK=true;
$location.path('/view/'+curriculumInfo.curriculum.id);
}
else{
$scope.curriculumInfo.statusOK = false;
$scope.curriculumInfo.errors = curriculumInfo.errors;
}
});
};
}

function EditCurriculumCtrl($scope, $http, $location, select2Options, $routeParams){

$scope.curriculumInfo = {};
$scope.curriculumInfo.statusOK = true;
$scope.select2Options = select2Options;
$scope.id = $routeParams.id;

$http.get('/bignibou/utils/findCurriculumById.json',{params: {id: $routeParams.id}}).success(
function(curriculum){
$scope.curriculumInfo.curriculum = curriculum;
});

$scope.editCurriculum = function(){
$http.post('bignibou/curriculum/edit/'+$routeParams.id, $scope.curriculumInfo)
.success(function(curriculumInfo) {
if(curriculumInfo.statusOK == true){
$scope.curriculumInfo.statusOK=true;
$location.path('/view/'+curriculumInfo.curriculum.id);
}
else{
$scope.curriculumInfo.statusOK = false;
$scope.curriculumInfo.errors = curriculumInfo.errors;
}
});
};
}

我不确定该怎么做,因为将成为命名回调函数的东西有几个依赖项(即 $scope 和 $location)。

如果我从 angularjs Controller 中提取函数(命名回调),那么命名回调不再访问其依赖项

谁能帮忙找出成功回调函数并确保满足依赖关系?

最佳答案

只需将它们作为参数传递即可。

首先,$http.post 期望回调接受一个参数。所以我们编写了 post 期望的函数:

function (curriculumInfo) {
// .....
}

但是函数体需要访问$scope$location。所以我们编写了一个函数来接受这些函数并返回 post 期望的函数:

function (scope,location) {
return function (curriculumInfo) {
// ... use scope and location in here
}
}

现在我们可以适本地命名函数了。让我们看看,它正在处理对新类(class)的响应,所以我将其称为 new_curriculum_callbacknew_curriculum_callbackhandle_new_curriculum 以表明它是一个回调:

function handle_new_curriculum (scope,location) {
return function (curriculumInfo) {
}
}

现在可以调用它返回回调函数给post:

$http
.post('bignibou/curriculum/new',$scope.curriculumInfo)
.success(handle_new_curriculum($scope,$location));

关于javascript - 将参数传递给 angularjs/javascript 中的命名回调函数的问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19664909/

30 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com