【问题标题】:Outsourcing implementation of a function contains $http, $scope and other parameters一个函数的外包实现包含$http、$scope等参数
【发布时间】:2016-09-06 12:14:04
【问题描述】:

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

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

$scope.UserHasBeenSelected = function (username) {

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

我的模板 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);

可以看出,我有一个包含代码的函数,如果给定了参数,我必须复制它来做同样的事情。

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

【问题讨论】:

    标签: javascript angularjs code-reuse


    【解决方案1】:

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

    【讨论】:

    • 但是我如何在“yourDuplicateMethod”中使用 $scope?因为我必须在我的代码中使用范围和 http 服务。
    • 您可以在自定义的“yourServiceName”服务中注入 $http 服务,并像在控制器中一样使用它。关于范围的使用...我认为您可以将其作为参数传递给“yourDuplicateMethod”,但我不确定这是否是一个好的设计理念。如果您提供更多重复代码的详细信息,也许我们可以帮助您重构它以使其更加模块化。您可以编辑您的问题和/或向我们提供您的代码的工作示例。亲切的问候。
    • 我将 http 和 scope 服务注入我自己的服务 (yourServiceName) 现在,我可以将它用作“真正的”功能。这很好。我现在有一些问题,但是在我消除了我的每一个问题之后,我会回到这里看看这个答案是否已经完成。
    • 我可以设法解决我所有的问题,所以我可以接受你的回答。感谢您的帮助和时间 :) 我学到了新东西。
    • 我很高兴它有帮助,我很高兴我可以教别人一个新东西:)。亲切的问候。
    猜你喜欢
    • 2014-06-22
    • 2021-09-10
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-11-21
    • 2016-03-12
    • 1970-01-01
    相关资源
    最近更新 更多