AngularJS: Read route param from within controller

后端 未结 2 1809
迷失自我
迷失自我 2021-02-02 01:01

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

相关标签:
2条回答
  • 2021-02-02 01:15

    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) {
       // ... 
    });
    
    0 讨论(0)
  • 2021-02-02 01:18

    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']}}
    
    0 讨论(0)
提交回复
热议问题