2016-06-06 3 views
0

나는 기본적으로 똑같은 작업을 수행하는 두 개의 컨트롤러가있는 저장 버튼이 있습니다. 그래서 컨트롤러를 사용할 수있는 재사용 가능한 함수에 넣고 싶습니다. 정상적인 함수를 만들고 $ 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); 
}]); 

답변

0

factory() service을 사용하십시오. 함수 세트를 정의하고이를 오브젝트로 리턴 할 수 있습니다. 이 개체는 모든 컨트롤러 내에서 주입 할 수 있습니다.

app.factory('sharedFactory', [function() { 
    "use strict"; 

    return { 
     myFunction: function() { 
      console.log("sharedFunction"); 
     } 
    }; 

}]); 

app.controller('AnyController', ['sharedFactory', function(sharedFactory) { 
    "use strict"; 

    sharedFactory.myFunction(); 

}]); 
+0

서비스를 만들 때 $ scope를 사용할 수없는 것처럼 보입니다. 모델 객체를 매개 변수로 서비스에 전달하는 방법이 있습니까? –

+0

서비스가 반환하는 함수에 $ scope 변수를 인수로 전달할 수 있습니다. 서비스에서 반환 된 함수의 함수 매개 변수로 $ scope를 정의하고 컨트롤러에서 객체를 전달하십시오. –

2

이 서비스를 사용할 수 있습니다. 서비스는 싱글 톤이므로 하나의 인스턴스 만 생성됩니다. 그리고 당신은 dependency injector에 의해 그것을 컨트롤러에 주입 할 수 있습니다. 당신은 더 here

1

당신은 공유 기능에 대한 서비스를 만들 수 있습니다 읽을 수

아래
var app=angular.module('app',[]) 

app.service('myService',function($http){ 

    this.saveLocation=function(){ 
    //Your code 
    } 

}); 

다음 컨트롤러에서 당신처럼 삽입 할 수와 같은 컨트롤러에 주입 할 수 아래

app.controller('myController',['$scope','myService',function($scope,myService){ 
//use myService function to call save functionality 
}]); 

또한 $ http를 사용하는 경우 약속을 반환하므로 성공한 콜백에서이 약속의 가치에 의존하는 모든 코드를 작성해야합니다. 그렇지 않으면 코드가이 콜백보다 먼저 실행됩니다 및 y ou에는 해당 변수에 대해 정의되지 않은 값이 있습니다.