AngularJS: Read route param from within controller

喜你入骨 提交于 2019-12-20 09:39:54

问题


How can a parameter from an URL be read within an AngularJS controller?

Let's say I have an URL like http://localhost/var/:value and I want the value to be stored in a variable within the controller for the /var/:value URL.

I have tried using $routeParams.value and $route.current.params.value but $routeParams is undefined at the beginning and $route doesn't work.


回答1:


The problem is that you probably inject $routeParams or $route in a controller that is run before a route change has occurred, e.g. your main/master/page controller.

If you inject $routeParams in a controller for a specific route (specified by the controller property when you define the route), then it will work, otherwise you're probably better of listening to the various events the route service broadcasts.

Try to change your code to use

$scope.$on('$routeChangeSuccess', function (ev, current, prev) {
   // ... 
});



回答2:


Requirements: Ensure 'ngRoute' is in your app module

Route provider set up as: http://localhost/var/:valName

Function set up as:

function functionName($scope, $routeParams){$scope.value = $routeParams.valName;}

HTML view:

{{value['valName']}}


来源:https://stackoverflow.com/questions/16263409/angularjs-read-route-param-from-within-controller

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!