一个函数的外包实现包含$http、$scope等参数

Outsourcing implementation of a function contains $http, $scope and other parameters

我正在尝试重用我的代码,但我不知道具体怎么做。

我有一个下拉列表,其中包含所有用户。如果我点击一个用户,

$scope.UserHasBeenSelected = function (username) {

运行。没关系。但是,如果用户在另一个页面上单击 link,我想获得相同的输出,并将用户重定向到该页面,但将所选用户名作为参数。为了能够做到这一点,我不得不复制代码......这基本上是一个糟糕的方法。

我的模板有一个控制器 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);

可以看出,我有一个包含代码的函数,如果给定了参数,则必须复制它才能执行相同的操作。

你知道如何将它外包为一个函数,并从控制器本身调用它吗?

看来您需要的是将重复代码移动到 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);