gpt4 book ai didi

javascript - 在 Angular 中创建函数

转载 作者:行者123 更新时间:2023-11-28 18:32:45 24 4
gpt4 key购买 nike

我有两个 Controller ,它们都有一个保存按钮,本质上做同样的事情。所以我想将它放在两个 Controller 都可以使用的可重用函数中。我尝试通过创建一个普通函数并传递模型对象以及 $http 来做到这一点,但该函数在按下保存按钮之前执行,导致所有参数都设置为未定义。我应该如何创建一个这两个 Controller 都可以使用的函数?

代码如下:

app.controller('addCtlr',['$scope','$http','$location',
function($scope, $http, $location){
$scope.save = function(){
var practices = [];
var url = "https://maps.googleapis.com/maps/api/geocode/json?address="+$scope.location.address.replace(/ /g,"+");


//If there are practices
if($scope.days){
for(dayName in $scope.days){ //Loop through the days object
var day = $scope.days[dayName]; //Gets the day pratice object
practices.push({day: dayName, start_time: day.startTime, end_time: day.endTime}); //Add the pratice object to the practices array
}
}
//Call to get the lat lng and formatted address from Google Map's service
$http.get(url)
.then(function(response){
locJSON = response.data.results[0]; //The JSON response

//createing an object to send to the backend to save
var locObj = {
name: $scope.location.name,
address: locJSON.formatted_address,
location: locJSON.geometry.location,
cost: $scope.location.cost,
practices: practices,
notes: $scope.location.notes
};

//Sending using POST since a new object is being created
$http.post('/api/locations', locObj)
.then(
$location.path('/')
);
});//*/
};
}]);

这就是我的函数的样子:

function saveLocation(location, days, $http){
var practices = [];
var url = "https://maps.googleapis.com/maps/api/geocode/json?address="+location.address.replace(/ /g,"+");


//If there are practices
if(days){
for(dayName in days){ //Loop through the days object
var day = days[dayName]; //Gets the day pratice object
practices.push({day: dayName, start_time: day.startTime, end_time: day.endTime}); //Add the pratice object to the practices array
}
}
//Call to get the lat lng and formatted address from Google Map's service
$http.get(url)
.then(function(response){
locJSON = response.data.results[0];

//createing an object to send to the backend to save
var locObj = {
name: location.name,
address: locJSON.formatted_address,
location: locJSON.geometry.location,
cost: location.cost,
practices: practices,
notes: location.notes
};

//Sending using POST since a new object is being created
$http.post('/api/locations', locObj)
.then(
//$location.path('/') //Redirects the user back to the homepage
);
});
}

这就是我在新 Controller 中调用该函数的方式:

app.controller('addCtlr',['$scope','$http','$location',
function($scope, $http, $location){
$scope.save = saveLocation(location, days, $http);
}]);

最佳答案

您可以为此使用服务。服务是单例的,因此只会创建一个实例。您可以通过依赖项注入(inject)器将其注入(inject)到 Controller 中。您可以阅读更多here

关于javascript - 在 Angular 中创建函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37661569/

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