Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
287 views
in Technique[技术] by (71.8m points)

javascript - Angular: Passing params from $routeProvider to controller

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

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

1 Reply

0 votes
by (71.8m points)

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); 
 }

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...