Angular: Passing params from $routeProvider to controller

前端 未结 4 1590
野性不改
野性不改 2020-12-13 01:54

I have multiple routes that invoke the same Controller and I would like to pass different variables to it.

// Example
$routeProvider.
  when(\'/a\', {
    te         


        
4条回答
  •  刺人心
    刺人心 (楼主)
    2020-12-13 02:37

    You can use resolve and $route.currrent.params.test to pass the parameter like this:

    $routeProvider
      .when('/a', {
        templateUrl: 'view.html',
        controller: 'MainCtrl',
        resolve: {
            test: function ($route) { $route.current.params.test = true; }
        }
      })
      .when('/b', {
        templateUrl: 'view.html',
        controller: 'MainCtrl',
        resolve: {
            test: function ($route) { $route.current.params.test = false; }
        }
      })
    

    Then in your controller you can access it from the $routeParams:

    app.controller('MainCtrl', function($scope, $routeParams) {
      $scope.test = $routeParams.test;
    })
    

    http://plnkr.co/edit/ct1ZUI9DNqSZ7S9OZJdO?p=preview

提交回复
热议问题