【发布时间】: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