The route parameters are malfunctioning

I've managed to get basic routing functionality working, but I'm encountering an issue when trying to include parameters in my routes. When I attempt to access routes with params, nothing appears inside my ngview.

var myApp = angular.module('myApp', ['ngRoute']);

myApp.config(function($routeProvider) {

    $routeProvider

    .when('/', {
        templateUrl: 'pages/main.html',
        controller: 'mainController'
    })

    .when('/second/:num', {
        templateUrl: 'pages/second.html',
        controller: 'mainController'
    })

});

myApp.controller('mainController',
    ['$scope', '$log', '$routeParams', function($scope, $log, $routeParams) {
    $scope.name = "Chris";
    alert($routeParams);
    $scope.num = $routeParams.num;
    $log.info($scope.num)
}]);

Whenever I try to navigate to /second/:num, nothing shows up in my ngview. Strangely, accessing either / or /second works perfectly fine.

Answer №1

Make sure to verify the controller in second.html page to ensure it has been properly added. It is recommended to always utilize different controllers for each template.

The preferred method is using stateProvider as it is easier and more flexible compared to routeProvider. Although both serve the same purpose, stateProvider tends to be more practical.

var myApp = angular.module('myApp', ['ngRoute']);

myApp.config(function($stateProvider) {

  $stateProvider
    .state('/', {
    templateUrl: 'pages/main.html',
    controller: 'mainController'
  })

  .state('/second/:num', {
    templateUrl: 'pages/second.html',
    controller: 'mainController'
  })

});
myApp.controller('mainController', ['$scope', '$log', '$stateParams', function($scope, $log, $stateParams) {
  $scope.name = "Chris";
  alert($stateParams);
  $scope.num = $stateParams.num;
  $log.info($scope.num)
}]);

Answer №2

It seems like there may be an issue with how you're specifying the path to your templates or possibly an error in your console log. Here is a snippet of your code, including the html files in ng-templates:

var myApp = angular.module('myApp', ['ngRoute']);

myApp.config(function($routeProvider) {

  $routeProvider

  .when('/', {
    templateUrl: 'main.html',
    controller: 'mainController'
  })

  .when('/second/:num', {
    templateUrl: 'second.html',
    controller: 'mainController'
  })

});
myApp.controller('mainController', ['$scope', '$location', '$log', '$route', '$routeParams', function($scope, $location, $log, $route, $routeParams) {
  $scope.name = "Chris";
  $scope.num = $routeParams.num || 'not defined';
  console.log($scope.num);
  
  $scope.goTo = function(number) {
    $location.path('/second/' + number);
  };
  $scope.route = $route.current;
  $scope.goHome = function(number) {
    $location.path('/');
  };
}]);
<!DOCTYPE html>
<html ng-app="myApp">

  <head>
    <script data-require="<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="4f2e21283a232e3d61253c0f7e617b6177">[email protected]</a>" data-semver="1.4.8" src="https://ajax.googleapis.com/ajax/libs/angularjs/1.4.8/angular.js"></script>
    <script data-require="<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="d2b3bcb5a7beb3a0ffa0bda7a6b792e3fce6fcea">[email protected]</a>" data-semver="1.4.8" src="https://code.angularjs.org/1.4.8/angular-route.js"></script>
  </head>

  <body ng-controller="mainController">
    <div ng-view></div>
    
    <script type="text/ng-template" id="main.html">
      <pre>route params: {{route.params}}</pre>
      This is the main page, where $scope.num is {{ num }}
      <ul>
        <li ng-repeat="num in [0,1,2,3, 'zebra']">
          <button ng-click="goTo(num)">{{ num }}</button>
        </li>
      </ul>
    </script>
    
    <script type="text/ng-template" id="second.html">
      <pre>route params: {{route.params}}</pre>
      This is the second page, where $scope.num is {{ num }}
      <br>
      <button ng-click="goHome()">Home</button>
    </script>
  </body>
</html>

Is there anything that catches your attention?

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Retrieve the values of private variables within a defined function

While experimenting with typescript, I have encountered an issue that I can't seem to resolve. My project involves using Angular, so I will present my problem within that context. Here is a snippet of my code: class PersonCtrl{ private $scope: I ...

What is the process for creating separate files for modal controllers?

I have an Angular application with multiple modals, and I am using AngularUI to handle the modal directive. http://angular-ui.github.io/bootstrap/ Currently, my main controllers are all located in the app.js file as routes. $routeProvider.when '/da ...

What error have I made in my AngularJS code?

I attempted to modify the module variable <ul> <li ng-controller="ulCtrl"><a ng- href="" class ="active" >{{customers}}</a></li> <li><a ng-href="#JOBS">JOBS</a></li> <li><a ng-href ...

Refresh Angular with HTML5 mode

I have disabled my # using html5 mode in Angular.js and am utilizing grunt and node as a development server. However, whenever I try to reload or refresh the page, I encounter a 404 error. Can anyone provide guidance on how to configure the node server in ...

What is the best way to input an HTML element into AngularJS code?

I am looking to integrate the html element into my angularjs code. Within my HTML, I have elements such as data-form-selector='#linechart_general_form' and data-url="{% url 'horizon:admin:metering:samples'%}" that I need to access withi ...

Is AngularJS limited to animating in just one direction?

Reordering 5 items in an array has led to a discovery - when shuffled, only the items with higher indexes have smooth animations while others simply jump to their new positions. <div ng-repeat="item in items track by item.value" class="TestItem" ng-sty ...

JSON schema for validating HTML forms

As someone new to Angular, I've been looking for ways to implement form validation using JSON schema with no luck so far. If anyone has any insights or solutions, I would greatly appreciate the help! ...

Steps for enlarging the size of a content popover

I'm trying to figure out how to adjust the height of a content popover so that the footer appears below it. When I increase the height of the content, the footer stays in the same position. Shouldn't it move after the ion-content or at the bottom ...

How to Use AngularJS $http Mock Respond to Simulate a Response with a `location` Header?

One interesting scenario I have encountered involves an API that returns a status code of 202 with no data. However, the response includes a header called "Location" which points to a specific URL. After browsing through the $httpBackend respond(...) docu ...

Creating a dynamic word cloud in D3: Learn how to automatically adjust font sizes to prevent overflow and scale words to fit any screen size

I am currently utilizing Jason Davies' d3-cloud.js to create my word cloud, you can view it here 1. I'm encountering an issue where the words run out of space when the initial window size is too small. To address this, I have a function that cal ...

Using Modal Functions in AngularJS Controller

I have been working on a project that utilizes the ui.bootstrap. As per the instructions from the tutorial I followed, my setup looks something like this: 'use strict'; angular.module('academiaUnitateApp') .controller('EntryCtr ...

What is the CSS method for altering the color of a slider's runnable track upon selection?

Seeking assistance in changing the slider track color upon selection. Struggling to achieve the desired outcome of altering the color as it slides. CSS: /* Custom Styles */ .text-size-slider { line-height: 100%; font-size: 14px; position: relative ...

"Encountering issues with AngularJS when attempting to send data through $http.post

I am currently working on an angular app where I need to post elements into a database. To achieve this, I have set up a modal that allows me to select courses which will then be posted using the $http.post method. Below is the function responsible for pos ...

Verifying the absence of query parameters in AngularJS forms

I have been working on a project that involves passing query parameters to the backend for searching purposes. These parameters are passed using the AngularJS $http.get method. Some of these parameters are not mandatory for the search, so I would like th ...

What causes a failed assertion to activate a promise catch block?

During my unit testing of an Angular application, I encountered some unexpected outcomes. After analyzing the issue, I was able to replicate the problem in a sample test case. The failure of the should.equal(true, false, 'should then') assertion ...

Is there a way to enlarge images when hovered using canvas?

I came across a fascinating example at the following link: , where the images expand when hovered over. I am aware that this can be achieved using jquery, but I have concerns about its speed and reliability. I would like to experiment with d3.js, although ...

Generating a New Form in AngularJs Dynamically from a Separate Input

Within my application, there is a number picker that lets users increase or decrease the value, thanks to Maike Daloo's contribution. Currently, I am exploring ways to iterate through the selected number and generate a form with input fields. This wi ...

Is Angular Translate susceptible to race conditions when using static files for multi-language support?

Currently utilizing angular translate with the static files loader for implementing multiple languages in my project. However, I've encountered a problem where the loading of language files sometimes takes longer than loading the actual view itself, l ...

Utilizing Angular.js to retrieve data from the server and automatically update at specified intervals

I attempted to create a basic app that displays the newest message from each member. Initially, it loads an array of members. Then I invoke a function called refreshMsg to iterate through the array. Within the iteration, I set a timer on it. Unfortunate ...

AngularJS is throwing an error because it can't find a function called 'undefined' in Controller xxx

Just diving into the world of Angular. I'm following an example from a reputable book, but encountering an issue with the Cart Controller not being recognized as a function. Here's the code snippet causing trouble: HTML: <!DOCTYPE html> & ...