【问题标题】:angular multiple routes sharing one controller共享一个控制器的角度多条路线
【发布时间】:2015-02-14 02:33:52
【问题描述】:

我不确定我是否正确地处理了这个问题,但我正在构建一个电子商务网站 - 该网站的一部分有 6 个不同的产品网格页面,每个页面都可以使用相同的视图:

<ul class="products row">
    <li class="product thumbnail col-1 grid" ng-repeat="whisky in whiskies | orderBy: sort">
        <p class="picture">
            <a ng-href="#/json/{{whisky.id}}"><img ng-src="images/scotch/{{whisky.imageUrl}}" alt="{{whisky.name}}"/></a>
        </p>
        <div class="desc">
            <h2>{{whisky.name}}</h2>
            <p class="price"><span>&pound;{{whisky.price}}</span></p>
        </div>
        <div class="actions">    
        <button class="add-to-basket btn btn-primary btn-medium fa fa-shopping-cart" data-item='{"imageUrl" : "{{whisky.imageUrl}}", "price" : "{{whisky.price}}", "startPrice" : "{{whisky.price}}", "name" : "{{whisky.name}}", "totalItems" : "{{1}}"}' ng-click="updateMiniBasket($event)"></button>    
        </div>
    </li>
</ul>

和同一个控制器:

whiskyControllers.controller('whiskyListCtrlr', ['$scope', 'whiskyList', '$http', 

    function($scope, whiskyList, $http){

        whiskyList.getWhiskies().then(function(d) {
            $scope.whiskies = d.data;
        })

    }

])

但需要在路线提供者配置中设置不同的路线,即一条去苏格兰威士忌,一条去爱尔兰,一条去日本等等。

如何对路由进行编码,以便不同的页面共享相同的控制器和视图?是否可以将参数从路由器传递到控制器?

非常感谢

【问题讨论】:

    标签: angularjs controller routes


    【解决方案1】:

    是的,您可以根据需要多次重复使用控制器和视图。如果我理解正确,您希望不同的路线使用相同的控制器和视图?这很简单。此外,您希望能够在触发路由时将变量传递给控制器​​吗?也很容易。这是一个不使用ui-router的示例。

    angular.module('myApp').config(['$routeProvider', 'whiskeyList', appConfig]); 
    
    function appConfig($routeProvider, wiskeyList) {
      $routeProvider
      .when('/scotch', {
        controller: 'whiskeyListCtrlr',
        resolve: {
          data: function(whiskeyList) {
            return whiskeyList.getWhiskeys();
          }
        }
      })
      .when('/irish', {
        controller: 'whiskeyListCtrlr',
        resolve: {
          data: function(whiskeyList) {
            return whiskeyList.getWhiskeys();
          }
        }
      });
    }
    

    显然,此实现不是 DRY(不要重复自己)。我会重新考虑你的实施。我会更改whiskeyList.getWhiskeys() 以接受一个参数,告诉它要返回的威士忌类型。例如,whiskeyList.getWhiskeys('scotch')。然后,您在控制器中收到的数据将被过滤为仅视图需要的数据。

    在路由器的解析函数中映射的数据在控制器中通过名称访问。

    whiskyControllers.controller('whiskyListCtrlr', ['$scope', 'data', function ($scope, data) {
      $scope.whiskeys = data;
    });
    

    【讨论】:

    • 对不起,其他评论有问题谢谢你,但我无法让它工作。到目前为止,我有: var WhiskyrumApp = angular.module('whiskyrumApp', ['ngRoute', 'ngResource', 'whiskyControllers']).config(['$routeProvider', 'whiskyList', appConfig]); 我已经将这个 when 添加到您的 appconfig 函数 when('/irish', { templateUrl : 'views/whisky-list.html', controller : 'whiskyListCtrlr', resolve : { data : function() { return whiskyList.getWhiskies('irish'); } } ). 并将数据参数添加到控制器中,但它抱怨那个威士忌列表不可用。
    • @MikeAlizade whiskeyList 是如何实现的?是服务还是工厂?你的配置函数上的参数是否正确?
    • 问题是我的app.js中config函数中传入的whiskylist参数(指的是一个服务)不被识别:var whiskyrumApp = angular.module('whiskyrumApp', ['ngRoute', 'ngResource', 'whiskyControllers']).config(['$routeProvider', 'whiskyList', appConfig]);这是因为此时service.js不存在加载是因为它是在 app.js 之后调用的,但是如果我将 services.js 放在 app.js 之上,那么像 whiskyrumApp.factory(... 这样调用的服务将无法识别whiskyrumApp var 不知道如何重组它,或者我应该使用工厂或服务。谢谢
    • @MikeAlizade 啊,是的。看看这些answers。看看有没有帮助。
    【解决方案2】:

    使用ui-router 很容易做到这一点,它比内置的角度路由提供了许多优势。 Ui Router 允许您通过指定模板和控制器来封装状态,并“解析”数据(基于路由或其他参数),然后您可以将其传递到控制器中。像下面这样的东西会很适合你:

    angular.module('whiskyApp')
        .config(['$stateProvider', function($stateProvider) {
            $stateProvider
            .state('whiskyList', {
    
                 // whisky-type is a catch all here - can be 'irish', 'japanese', anything.
                 // can also use regex to restrict it a bit
                 url: '/lists/:whiskyType',
                 templateUrl: 'whisky-list-template.html',
                 controller: 'whiskyListCtrl',
    
                 // this is what gets passed to the controller
                 resolve: {
                     type: ['$stateParams', function($stateParams) {
    
                         // pass the whisky type from the url into the controller
                         return $stateParams.whiskyType;
                     }],
                     list: ['$stateParams', 'whiskyList', function($stateParams, whiskyList) {
    
                         // we can also go ahead and pass in the resolved list - this is best practice
                         return whiskyList.getWhiskies();
                     }]
                 }
            });
        }]);
    
    ]);
    

    然后在您的控制器中,只需注入“resolve”映射的键名即可使用它们:

    whiskyControllers.controller('whiskyListCtrlr', ['$scope', 'list', 'type' '$http', 
    
        function($scope, list, type, $http){
           $scope.whiskies = list;
           $scope.type = type;
        }
    ])
    

    【讨论】:

    • 感谢您的帮助,但选择了下面的非 ui-router 方法
    猜你喜欢
    • 1970-01-01
    • 2023-03-27
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-11-11
    • 2018-11-26
    相关资源
    最近更新 更多