在AngularJS中定义路由时如何减少代码冗余

时间:2015-05-18 18:57:00

标签: angularjs rest angular-resource angular-routing

我目前正在编写AngularJS中的Rest API和客户端。我正在使用Angular模块

  • angular-resource(ngResource)
  • angular-route(ngRoute)

这是我的路由配置的样子:

$routeProvider
.when('/facility', {
    templateUrl: pathTemplate + 'Facility/index.html',
    controller: 'FacilityIndexController',
    resolve: {
        Facilities: ['Facility', function(Facility) {
            return Facility.query();
        }]
    }
})
.when('/facility/show/:id', {
    templateUrl: pathTemplate + 'Facility/show.html',
    controller: 'FacilityShowController',
    resolve: {
        Facility: ['Facility', '$route', function(Facility, $route) {
            return Facility.get({id: $route.current.params.id});
        }]
    }
})
.when('/facility/edit/:id', {
    templateUrl: pathTemplate + 'Facility/edit.html',
    controller: 'FacilityEditController',
    resolve: {
        Facility: ['Facility', '$route', function(Facility, $route) {
            return Facility.get({id: $route.current.params.id});
        }]
    }
})

这只是一个实体。另外,我需要为每个“动作”定义一个控制器。我把它们放在一起用于这个单一的实体:

'use strict';
angular.module('app')
.controller('FacilityIndexController', ['$scope', 'Facilities', function($scope, Facilities) {
    $scope.facilities = Facilities;
}])
.controller('FacilityShowController', ['$scope', 'Facility', function($scope, Facility) {
    $scope.facility = Facility;
}])
.controller('FacilityCreateController', ['$scope', 'Facility', function($scope, Facility) {
    $scope.facility = new Facility();
    // $scope.facility.$save();
}])
.controller('FacilityEditController', ['$scope', 'Facility', function($scope, Facility) {
    $scope.facility = Facility;

    $scope.update = function() {
        var id = $scope.facility.id;
        $scope.facility.$update({id: id}).then(function(response){
            $scope.goTo('facility/show/' + id);
        });
    };
}]);

我认为使用$resource非常酷,因为一切都会自动运行......好吧,只有冗余非常高。

你有最好的做法吗? 提前谢谢。

1 个答案:

答案 0 :(得分:0)

你总是可以在某些服务/工厂中取出Facility.get({id: $route.current.params.id});的逻辑,但这样就会过度工程化。除此之外,我没有看到太多冗余,因为大多数代码只是声明事物。