AngularJS为一个控制器使用多个服务的方法?

时间:2013-11-30 10:52:24

标签: angularjs laravel-4

我不知道这是否适合提问,但现在是:

我的应用程序包含许多不同的表单,我想使用angular(和laravel)提交它们,这就是它的样子:

app.controller("uploadController", ['$scope', '$sanitize', '$location', 'UploadService', 
    ($scope, $sanitize, $location, UploadService) -> 
        $scope.upload = ->
            formType = $sanitize($scope.formType)
            ##switch case for `UploadService` to gain data of what form it is
            ##Ex:
            ###
                switch(formType): {
                    case ('uploadFormNews'):
                        UploadService.save
                            data1: $sanitize($scope.data1)
                            data2: $sanitize($scope.data2)
                        , (->
                            $scope.alert = ''
                        ), (response) ->
                            $scope.alert = response.data.alert
                        break;
                    case ('uploadFormMember'):
                        UploadService.save
                            data3: $sanitize($scope.data3)
                            data4: $sanitize($scope.data4)
                        , (->
                            $scope.alert = ''
                        ), (response) ->
                            $scope.alert = response.data.alert
                        break;
                }
            ###
])

现在我的问题是,如何为这些不同的案例确定不同的服务?我试过这个:

app.factory("UploadService", ['$resource', ($resource) ->
    $resource "upload/news" //for news form
    $resource "upload/member" //for member form
])

显然它不起作用,有些东西不完整(比如知道哪个case将使用$resource)。有什么方法吗?谢谢你的帮助

1 个答案:

答案 0 :(得分:3)

如果我正确理解了这个问题。您的工厂应该返回一个对象,并定义这些资源。

app.factory("UploadService", ['$resource', function($resource)
{
return  {
    news:$resource("upload/news"), //for news form
    member:$resource("upload/member") //for member form
}
}]);

我是控制器然后你打电话

UploadService.news.save(data); //For saving news

UploadService.member.save(data); //For saving member