使用不同参数重用Angular视图和控制器

Vic*_*and 0 javascript angularjs

我正在使用Angular 1前端,与一个非常标准的REST-ish API交谈.一般结构由简单的HTML视图组成,相应的控制器与一些基本URL相交,在没有每个控制器的情况下通常保持相同,例如/customer在这个简化的示例中:

调节器

app.controller('customerCtrl', function($scope, $http) {
    $scope.loadCustomer = function() {
        $http.get('/customer/'+$scope.id) 
             .then(function(response) {
                 $scope.customer = response.customer;
             });
    };
    $scope.loadCustomerData = function() {
        $http.get('/customer/'+$scope.id+'/data') 
             .then(function(response) {
                 $scope.customerData = response.data;
             });
    };
});
Run Code Online (Sandbox Code Playgroud)

视图

<div ng-controller="customerCtrl">
    <input type="text" ng-model="id"></input>
    <button ng-click="loadCustomer()">Load Customer</button>
    <div>{{ customer.name }}</div>
    ...
    ...
</div>
Run Code Online (Sandbox Code Playgroud)

等等.实际文件长度为几百行.现在突然间,一组新用户需要访问该应用程序.前端视图和控制器逻辑是相同的,但它们跟一个不同的后端基本URL,例如/externalCustomer.加载函数调用将改为$http.get('/externalCustomer/'+$scope.id),等等.

意见还需要不同的URL.如果访问当前视图http://app.com/#/customerView,新的视图将在http://app.com/#/externalCustomerView.

鉴于有更多这样的视图和控制器方法(带有硬编码的后端URL),我宁愿不复制和粘贴几百行并且逻辑分歧,实现这个的正确方法是什么?能够重用视图和控制器并且可能传递一些基本URL参数和/或视图URL会很棒,但我不知道如何开始.

小智 5

在你的路线

$routeProvider
        .when('/:baseUrl', {
            templateUrl: 'public/app/customerView.html',
            controller: 'customerViewCtrl',
            controllerAs: 'customerViewCtrl'                           
            }
        });
Run Code Online (Sandbox Code Playgroud)

并在你的控制器中注入$ route并读取'baseUrl'参数

$http.get('/'+$route.current.params.baseUrl+'/'+$scope.id+'/data') 
         .then(function(response) {
             $scope.customerData = response.data;
         });
Run Code Online (Sandbox Code Playgroud)

通过这种方式,当您传递externalCustomer时,将用于baseURL,同样用于客户

另一种方法可以是这样的:

$routeProvider
        .when('/customerView', {
            templateUrl: 'public/app/customerView.html',
            controller: 'customerViewCtrl',
            controllerAs: 'customerViewCtrl',
            baseUrl: 'customer'               
            }
        }).when('/externalCustomerView', {
            templateUrl: 'public/app/customerView.html',
            controller: 'customerViewCtrl',
            controllerAs: 'customerViewCtrl',
            baseUrl: 'externalCustomer'                
        })
Run Code Online (Sandbox Code Playgroud)

并在你的控制器中注入$ route并读取'baseUrl'为

$http.get('/'+$route.current.baseUrl+'/'+$scope.id+'/data') 
         .then(function(response) {
             $scope.customerData = response.data;
         });
Run Code Online (Sandbox Code Playgroud)