Passing data to an Angular controller through the router: A step-by-step guide

Data Table Overview:

--------------------------------------------------------------------
| ID | PARENT ID | CATEGORY        | URL                           |
--------------------------------------------------------------------
| 1  | 0         | Programming     | programming                   |
-------------------------------------------------------------------- 
| 2  | 1         | Logic           | programming/logic             |
--------------------------------------------------------------------
| 3  | 1         | Object-Oriented | programming/oop               |
--------------------------------------------------------------------
| 4  | 2         | PROLOG          | programming/logic/prolog      | 
--------------------------------------------------------------------
| 5  | 2         | LISP            | programming/logic/lisp        |
--------------------------------------------------------------------
| 6  | 3         | JAVA            | programming/oop/java          |
--------------------------------------------------------------------
| 7  | 3         | C#              | programming/oop/csharp        |
--------------------------------------------------------------------

Page Configuration:

<html>
    <body>
        <nav ng-controller="navController">
            <ul ng-repeat="menuItem in menuItems">
                <li><a href="#/{{menuItem.URL}}">{{menuItem.Title}}</a></li>
            </ul>
        </nav>

        <div ng-view>
        </div>
    </body>
</html>

Context Explanation:

The navigation menu is dynamically generated from database information, providing drill-down functionality to display one level at a time.

The initial level showcases one menu item:

<ul>
    <li>
        <a href="#/programming">Programming</a>
    </li>
<ul>

Upon clicking the "Programming" link, subsequent children of that menu item are revealed:

<ul>
    <li>
        <a href="#/programming/logic">Logic</a>
    </li>
    <li>
        <a href="#/programming/object-oriented">Object-Oriented</a>
    </li>
</ul>

Key Assumptions:

(1) Each menu item corresponds to a related partial. For instance, "Object-Oriented" links to its partial at: "/partials/objectoriented.html".

(2) The function GetMenuItemsByUrl(url) returns all children of a menu based on the provided url. For example, passing "programming/logic" retrieves rows 4 and 5 as children of row 2. This function is accessible via /api/GetMenuItemsByUrl/:url


Intended Behavior:

If the user navigates to: mywebsite.com/#/programing

(1) The displayed nav should include:

  • Logic
  • Object-Oriented

(2) The template loaded in the view should be: /templates/programming.html


Question Raised:

While I understand how to render views with the route through the router, my query pertains to passing the current url to the navController for a rebind request?

Answer №1

Check out the example I created based on my interpretation of your problem here

If you want to achieve unlimited nesting of routes, you can set up a catch-all route like this:

$routeProvider
.when('/:url*', {templateUrl: function(args) {
    return 'programming.tpl.html';
}, controller:'NavController'});

This approach will capture the entire URL as a parameter that can then be accessed in a controller using $routeParams.url.

 app.controller('NavController', function($scope, $routeParams, MenuService) {
    $scope.menuItems = MenuService.getMenuItems($routeParams.url);
    ...
 }

The MenuService is responsible for handling all the logic related to retrieving menu items based on the URL.

This example is straightforward and provides basic functionality when it comes to validation and mapping URLs to items. Let me know if you have more specific questions.

Answer №2

In order to accomplish this task, it is necessary to utilize $routeParams within the controller.

HTML Markup:

<a href="#/page/{{vm.item.id}}" class="btn btn-primary">

RouteProvider Configuration:

url: '/page/:id

Within the controller:

var pageId = $routeParams.id

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

Error: Attempts to access the 'avatar' property of a null value result in a TypeError

I've been attempting to showcase both an avatar and the user name, but I keep encountering this error. Despite trying to declare a user variable to troubleshoot, it's not resolving the issue. Error: Cannot read property 'avatar' of n ...

Manipulate CSS classes in an ng-repeat list using AngularJS

Dear colleagues, let's take a look at this clear example. [...document.querySelectorAll('.li-example')].forEach((s, i, arr) => { s.addEventListener('click', function() { [...document.querySelectorAll('.li-example&a ...

Exploring the functionality of iterating through a JSON array of objects with a foreach loop in both JavaScript and Jade

I have a json array that I am trying to display using foreach loop. However, it takes five iterations to show all the data when I would like it to be displayed in a single iteration. How can I achieve this? Below is the jade file code snippet: each item i ...

Is it possible to automatically adjust the text color to match the background color?

In my hypothetical scenario, I am part of a group chat where the owner has the ability to change the background color of the chat bubbles. Each user's username appears on top of their respective bubble in one of ten pre-assigned colors. However, not a ...

What is the best way to transfer data between windows using titanium (classic)?

'The code I've written utilizes MyHTTPlink to retrieve information such as Restaurant Name, url, and address. Currently, it lists all restaurant names and urls in a table. Now, I want to figure out how to send the details of a table row to the ne ...

Selecting a unique element at random from an array in Javascript

I want the function to randomly select elements from the array without repetition function RandomSelect() { let names = ["Yazeed", "Ammar", "Marwan", "Othman", "Sameh", "Amro", "Ibraheem"]; let paragraph = document.getElementById("demo1"); l ...

The functionality of List.js is currently not optimized for use with tables

I'm currently experimenting with list.js in order to create a real-time search feature for a table. I have successfully tested it on lists (similar to the example provided at ). However, I am facing difficulty replicating this functionality for tables ...

Arranging data in a table using PHP

After some thorough research, I am finally prepared to dive into the world of PHP. My project involves an HTML5 animation with table sorting functionalities - one button for sorting by date and another for sorting by title. Despite my efforts to find a cus ...

Utilize jQuery's addClass Method when Submitting a Form Using Ajax

When the form is submitted, I would like to add a class and display a loading animation before executing the AJAX request. However, when setting async to false in the AJAX call, the AJAX request will be executed first before displaying the loading animatio ...

Navigating to an AngularJS state through an email hyperlink

Trying to guide users from an email link to a specific state within my Angular app presents a challenge due to its single page nature, making direct URL redirection impossible. Past attempts involved utilizing URL parameters: The email includes this link ...

Authenticate users using JavaScript usernames

Below is my registration link that opens a modal: <a href="#registermodal" data-toggle="modal">Register Here</a> Here is the code for the modal dialog: <div class="modal fade" id="registermodal" role="dialog" style="overflow: scroll;"> ...

Here's a step-by-step guide on how to parse JSON information in JavaScript when it's formatted as key-value

I need to parse the JSON data in JavaScript. The data consists of key-value pairs. Data looks like this: {09/02/2014 15:36:25=[33.82, 33.42, 40.83], 08/11/2014 16:25:15=[36.6, 33.42, 40.45], 07/30/2014 08:43:57=[0.0, 0.0, 0.0], 08/12/2014 22:00:52=[77.99 ...

Mastering the art of using res.send() in Node.js

I have been working on a project using the mongoose API with Node.js/Express. There seems to be an issue with my get request on the client side as the data is not coming through. Can someone help me figure out what's wrong? Snippet of backend app.ge ...

Leveraging Promises within if conditions

Has anyone encountered difficulties using Promises within an if condition? I'm currently dealing with a problem where the code continues to execute even when the if statement is false. Any suggestions on how to resolve this issue? For a detailed exam ...

An issue with Node.js: "Foreach function not available" error

Having some trouble with parsing a nested JSON object from an API call. The error message foreach is not being recognized as a function. request(options, function (error, response, body) { if (error) throw new Error(error); console.log(body); ...

Ways to transfer a v-model from the parent component to a template

I'm currently in the process of designing the user interface for a search page and I want to utilize components to help with code reusability. However, I am facing a challenge in figuring out how to pass the model of the page to the search component. ...

Leveraging require in AWS lambda operations

As part of my exploration into AWS Lambda functions, I've been trying to determine if the require statement can be used within them. This would allow me to incorporate other non-lambda functions into my code. Although zipping the node modules folder i ...

Issue with displaying value after rendering

After fetching pool data from the constants file, my task was to create a featured vault - the one with the highest APY Reward value obtained from the API. Even though I successfully fetched all three values and performed the calculations, I am facing an i ...

What is the best way to ensure a jQuery function runs on duplicated elements?

I have been attempting to construct a webpage featuring cascading dropdowns using jQuery. The goal is to generate a duplicate set of dropdowns when the last dropdown in the current set is altered. I aim for this process to repeat up to 10 times, but I cons ...

What is the specific character code assigned to the "Enter" key on a

Check out this code snippet: http://jsfiddle.net/YttKb/ In my javascript, I am trying to add a new line of text using utf-8 coding. Which character should I use to make a new line? It seems like \n only creates a line break, not a new line of text. ...