2016-09-06 6 views
0

코드를 재사용하려고하는데 정확히 어떻게해야하는지 모르겠습니다.

모든 사용자가 포함 된 드롭 다운 목록이 있습니다. 사용자를 클릭하면

$scope.UserHasBeenSelected = function (username) { 

실행됩니다. 괜찮아. 그러나 사용자가 다른 페이지의 링크를 클릭하고 사용자를이 페이지로 리디렉션하지만 선택된 사용자의 이름을 매개 변수로 갖는 경우 동일한 출력을 얻고 싶습니다. 그것을 할 수 있기 위해서, 나는 코드를 복제해야만했다. 기본적으로 나쁜 접근이다.

I는 다음과 같습니다 내 템플릿 HTML을위한 컨트롤러를 가지고 :

var MonthlySummaryController = function ($scope, $http, $stateParams) { 

//FILL IN the drop-downList 
$http.get('DataProviderService.asmx/GetUsersAndTheirState') 
.then(function (response) { 
    $scope.users = response.data; 
}); 

//COPY-PASTE From HERE 
if ($stateParams.userName) { 
    //Do something with the username 
    ... 
} 
//COPY-PASTE To HERE 
... 

// if a user has been picked: (This is the method which can be called outside the HTML) 
$scope.UserHasBeenSelected = function (username) { 
    //Do THE SAME with the username as before. (This is the inner code which is duplicated) 
    ... 
} 

angular.module("Home").controller("monthlySummaryController", MonthlySummaryController); 
에서 볼 수있는 바와 같이

, 내가 코드를 포함하는 기능을 가지고 있고,이 경우 동일한 기능을 수행 할를 복제했다 매개 변수가 주어진다.

함수로 아웃소싱하는 방법을 알고 컨트롤러 자체에서 호출하는 방법이 있습니까?

답변

0

당신이 필요로하는 것은 중복 코드를 service으로 옮기는 것입니다. 이 같은 서비스를 만들 수 있습니다

yourApp.service('yourServiceName', function() { 
    return { 
     yourDuplicateMethod: function (userName) { 
      // Do all the stuff with the username here... 
     } 
    } 
}); 

을 그리고 그것을 주입 사용 컨트롤러에서 사용 :

var MonthlySummaryController = function ($scope, $http, $stateParams, yourServiceName) { 

//FILL IN the drop-downList 
$http.get('DataProviderService.asmx/GetUsersAndTheirState') 
.then(function (response) { 
    $scope.users = response.data; 
}); 

//COPY-PASTE From HERE 
if ($stateParams.userName) { 
    yourServiceName.yourDuplicateMethod($stateParams.userName); 
} 
//COPY-PASTE To HERE 
... 

// if a user has been picked: (This is the method which can be called outside the HTML) 
$scope.UserHasBeenSelected = function (username) { 
    yourServiceName.yourDuplicateMethod(userName); 
} 

angular.module("Home").controller("monthlySummaryController", MonthlySummaryController); 
+0

그러나이 어떻게 "yourDuplicateMethod"에서 $ 범위를 사용할 수 있을까? 내 코드에서 scope와 http 서비스를 사용해야하기 때문이다. –

+0

사용자 지정 'yourServiceName'서비스에 $ http 서비스를 삽입하여 컨트롤러에서와 동일한 방식으로 사용할 수 있습니다. 범위 사용에 관해서 ... 나는 당신을 'yourDuplicateMethod'에 대한 매개 변수로 전달할 수 있다고 생각하지만 좋은 디자인 아이디어인지 확실하지 않습니다. 중복 코드에 대한 세부 정보를 좀 더 제공한다면 모듈화를 위해 리팩터링 할 수 있습니다. 질문을 편집하거나 코드의 실례를 보여주는 플 런커를 제공 할 수 있습니다. 친절합니다. –

+0

내 서비스 (yourServiceName)에 http 및 범위 서비스를 주입했습니다. 이제는이를 "실제"기능으로 사용할 수 있습니다. 어느 쪽이 좋다. 지금 당장 몇 가지 질문이 있지만, 각 문제를 해결하고 나면이 답이 성취되었는지 여부를 알아보기 위해 여기로 돌아갈 것입니다. –