Angular $ routeParams is empty

I have a url that is passed to my Angular code via Rails. However, when I try to select a parameter in the url, it shows up as empty. Can anyone help me?

Example URL: http://localhost:3000/events/event1

Plnkr: http://plnkr.co/edit/yG8wAZHhgPtH2PBFzql3?p=preview

Angular:

eventsApp = angular.module('EventsApp', ['ngRoute'])


eventsApp.config [
    '$routeProvider'
    '$locationProvider'
    ($routeProvider, $locationProvider) ->
        $locationProvider.html5Mode(true)
        $routeProvider.when '/events/:eventName',
            templateUrl: '../../views/events/events.html.erb'
            controller: 'EventsCtrl'            
        return
]

eventsApp.controller('EventsCtrl',  [ 
    '$scope'
    '$routeParams'
    ($scope, $routeParams) ->       
        console.log($routeParams.eventName) # shows up as undefined
        $scope.greeting = $routeParams.eventName
])

      

HTML:

events.html.erb

    <div>
        {{greeting}}
    </div>

      

application.html.erb (general layout)

<div id="content" ng-app="EventsApp">
        <div ng-view></div>
        <%= yield %>
    </div>

      

Edit: as suggested, I moved ng-app

and ng-view

into layout and only kept the div inside events.html.erb

+3


source to share


2 answers


This is because you included a controller with a directive ng-controller

instead ng-view

. It should be like this:

<body ng-app="EventsApp">
    <div ng-view></div>
</body>

      



In events.html.erb

:

<div>
    {{greeting}}
</div>

      

+2


source


If the errors noted by Karaxuna still give you an empty result, it may be due to asynchronous work $routeParams

$routeParams

it usually takes some time to load. It loads asynchronously. When you try to use it, it may not be ready and is still empty. One approach is to create an event listener when the route is ready.



$scope.$on('$routeChangeSuccess', function() {
  console.log($routeParams.eventName);
});

      

+2


source







All Articles