Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

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

// Example
$routeProvider.
  when('/a', {
    templateUrl: 'test.html',
    controller: 'MyController' // should get passed 'exampleA'
  }).
  when('/b', {
    templateUrl: 'test.html',
    controller: 'MyController' // should get passed 'exampleB'
});

I know that I could use the "resolve" object:

$routeProvider.
  when('/a', {
    templateUrl: 'test.html',
    controller: 'MyController',
    resolve: {test: function() { return true; }}
});

To pass a value as a dependency:

app.controller('MyController', ['$scope', 'test', function ($scope, test) {
  console.log(test); // true
}

My problem with that approach is that my app crashes if the resolve object is missing on other routes and I would like to pass optional params.

Is there any way to pass specific params to the Controller (from the route provider)?


Thank you

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
268 views
Welcome To Ask or Share your Answers For Others

1 Answer

Routing:

$routeProvider.
  when('/a', {
    templateUrl: 'test.html',
    controller: 'MyController',
    paramExample: 'exampleA'
  }).
  when('/b', {
    templateUrl: 'test.html',
    controller: 'MyController',
    paramExample: 'exampleB'
});

Access: inject $route in your controller then use this

 app.controller('MyController', ['$scope', '$route', function ($scope, $route) {
      var paramValue = $route.current.$$route.paramExample;
      console.log(paramValue); 
 }

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...