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

时间:2017-04-04 06:41:06

标签: 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;
             });
    };
});

查看

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

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

视图还需要不同的网址。如果访问http://app.com/#/customerView处的当前视图,则新视图将位于http://app.com/#/externalCustomerView

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

1 个答案:

答案 0 :(得分:5)

在您的路线中

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

并在您的控制器中注入$ route并阅读&#39; baseUrl&#39; param as

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

以这种方式传递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'                
        })

并在您的控制器中注入$ route并阅读&#39; baseUrl&#39;如

$http.get('/'+$route.current.baseUrl+'/'+$scope.id+'/data') 
         .then(function(response) {
             $scope.customerData = response.data;
         });
相关问题