将可选参数传递给AngularJS中的controller.js

时间:2014-02-07 20:18:06

标签: javascript angularjs

我在AngularJS的controller.js文件中有这段代码:

app.controller('MetaDetailGroupList', ['$scope', '$http', function($scope, $http) {
        $http.get(Routing.generate('meta-detail-group-list')).success(function(data) {
            $scope.MetaDetailGroup = data;
            $scope.orderProp = 'name';
            $scope.currPage = 0;
            $scope.pageSize = 10;

            $scope.totalMetaDetailGroup = function() {
                return Math.ceil($scope.MetaDetailGroup.entities.length / $scope.pageSize);
            };

        }).error(function(data, status, headers, config) {
            $scope.MetaDetailGroup.message = "Ocurrieron errores al procesar los datos, por favor vuelva a intentarlo.";
        });
    }]);

我使用此函数来构建项目列表,它工作正常。其中一些项目有parent >> children关系,所以我需要再次调用相同的函数,但这次传递和ID作为可选参数来获得正确的子项,所以唯一的变化是这一行:

From: $http.get(Routing.generate('meta-detail-group-list')).success(function(data)

To: $http.get(Routing.generate('meta-detail-group-list' + '/'+id)).success(function(data) 

如果不为此只写另一个函数,我怎么能这样做呢?

1 个答案:

答案 0 :(得分:1)

我建议您将$ http调用移动到服务并处理id处理内容:

app.service('MetaDetailGroupListService',function($http) {
    return {
        metaDetailGroupList : function(_id) {
            var _s = (typeof _id === 'undefined') ?
                'meta-detail-group-list' :
                'meta-detail-group-list' + '/' + _id;
            return $http.get(Routing.generate(_s));
        }
    }
});

app.controller('MetaDetailGroupList', ['$scope', 'MetaDetailGroupListService',
function($scope, MetaDetailGroupListService) {
    MetaDetailGroupListService.metaDetailGroupList(id).success(function(data) {
        $scope.MetaDetailGroup = data;
        $scope.orderProp = 'name';
        $scope.currPage = 0;
        $scope.pageSize = 10;

        $scope.totalMetaDetailGroup = function() {
            return Math.ceil($scope.MetaDetailGroup.entities.length / $scope.pageSize);
        };

    }).error(function(data, status, headers, config) {
        $scope.MetaDetailGroup.message = "Ocurrieron errores al procesar los datos, por favor vuelva a intentarlo.";
    });
}]);