我正在尝试重用我的代码,但我不知道具体如何做到这一点。
我有一个下拉列表,其中包含所有用户。如果我单击某个用户,
$scope.UserHasBeenSelected = function (username) {奔跑。这很好。但是,如果用户单击不同页面上的链接,并将用户重定向到此页面,但将所选用户的姓名作为参数,我希望得到相同的输出。为了能够做到这一点,我必须复制代码...这基本上是一种糟糕的方法。
我的模板html有一个Controller,它看起来像这样:
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);可以看到,我有一个包含代码的函数,如果有给定的参数,则必须复制它来执行相同的操作。
您是否知道如何将其作为一个函数外包,并从控制器本身调用它?
发布于 2016-09-06 20:26:42
看起来你需要做的就是把重复的代码移到一个service中。您可以像这样创建一个服务:
yourApp.service('yourServiceName', function() {
return {
yourDuplicateMethod: function (userName) {
// Do all the stuff with the username here...
}
}
});然后使用inject it并在您的控制器中使用它:
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);https://stackoverflow.com/questions/39348807
复制相似问题