나는 기본적으로 똑같은 작업을 수행하는 두 개의 컨트롤러가있는 저장 버튼이 있습니다. 그래서 컨트롤러를 사용할 수있는 재사용 가능한 함수에 넣고 싶습니다. 정상적인 함수를 만들고 $ http뿐만 아니라 모델 객체를 전달하여이 작업을 시도했지만 저장 버튼을 누르기 전에 함수가 실행 중이며 모든 매개 변수가 정의되지 않은 상태로 설정됩니다. 어떤 방법으로이 컨트롤러가 사용할 수있는 함수를 만들어야합니까? 여기각도로 함수 만들기
코드를 보는 방법 :
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
);
});
}
이 내가 새로운 컨트롤러에있는 함수를 호출 한 방법입니다
app.controller('addCtlr',['$scope','$http','$location',
function($scope, $http, $location){
$scope.save = saveLocation(location, days, $http);
}]);
서비스를 만들 때 $ scope를 사용할 수없는 것처럼 보입니다. 모델 객체를 매개 변수로 서비스에 전달하는 방법이 있습니까? –
서비스가 반환하는 함수에 $ scope 변수를 인수로 전달할 수 있습니다. 서비스에서 반환 된 함수의 함수 매개 변수로 $ scope를 정의하고 컨트롤러에서 객체를 전달하십시오. –