首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >函数的外包实现包含$http、$scope等参数

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

Stack Overflow用户
提问于 2016-09-06 20:14:05
回答 1查看 38关注 0票数 0

我正在尝试重用我的代码,但我不知道具体如何做到这一点。

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

代码语言:javascript
复制
$scope.UserHasBeenSelected = function (username) {

奔跑。这很好。但是,如果用户单击不同页面上的链接,并将用户重定向到此页面,但将所选用户的姓名作为参数,我希望得到相同的输出。为了能够做到这一点,我必须复制代码...这基本上是一种糟糕的方法。

我的模板html有一个Controller,它看起来像这样:

代码语言:javascript
复制
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);

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

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

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2016-09-06 20:26:42

看起来你需要做的就是把重复的代码移到一个service中。您可以像这样创建一个服务:

代码语言:javascript
复制
yourApp.service('yourServiceName', function() {
    return {
        yourDuplicateMethod: function (userName) {
            // Do all the stuff with the username here...
        }
    }
});

然后使用inject it并在您的控制器中使用它:

代码语言:javascript
复制
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
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/39348807

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档