Setting up dynamic routing in AngularJS for links

I am facing some confusion regarding routing in AngularJS.

Normally, we can configure routes in angular.config() when the angular module is loaded. At that time, we define static information such as routePath, templateUrl, and controller.

However, I am unsure about how to dynamically configure routes with changing templateUrl and controller based on certain conditions.

For instance, I have a list of features (links) that should be displayed after the user logs in, depending on their assigned role.

The list of userfeatures looks like this: [{name:menu1, link:link1,...}, {name:menu2, link:link2,...}, {name:menu3, link:link3,...}...]

These features need to be loaded when the page is initially loaded, which is done through the controller at that time.

So, my question is - is it possible to dynamically configure route links? And how can I determine the correct templateUrl and controller when a link is clicked?

Here's what I have tried so far (code snippet):

<body ng-app="myApp">

<div ng-controller="c1" directive-to-show-menus-and-its-showing></div>

<div ng-view></div>

<script>
var app = angular.module("myApp", ["ngRoute"]);

var $routeProvider1;

app.config(function($routeProvider) {
$routeProvider1 = $routeProvider;
});

app.controller('c1', function($http, $route, $rootScope){

//var ar = {"/":"main.htm","/red":"red.htm","/green":"green.htm","/blue":"blue.htm"};
var userfeatures = [{name: Red, link: red}, {name: Green, link: green}, {name: Blue, link: blue}]; //actually its huge

for(var i in userfeatures) {

$routeProvider1.when("#!" + userfeatures[i].link,{
'templateUrl': 'it should be dynamic', //(how to attach templateUrl in controller of its)
'controller': common_controller   //it would be good with dynamic controller
});

}

});

function common_controller(){
// how to get clicked link info to extract certain info.
}
</script>

Answer №1

To improve your code organization, it is recommended to divide it into 3 segments:

1- Your main application file (e.g., application.js)

2- Your routing file (e.g., Routing.js)

3- Your URL records (Url.json)

Assuming your main controller is configured and ready for action.

Here is an example of how your URL.json should be structured:

{
"links" : [
{
    "Url": "/page/page1.html",
    "Controller": "Controller1"
},
{
    "Url": "/page/page2.html",
    "Controller": "Controller2"
}
]}

In your Routing.js file, you need to map the routes with the template files and retrieve data from the JSON file using HTTP requests.

Myapp.config(['$stateProvider', '$urlRouterProvider', '$locationProvider',
        function ($stateProvider, $urlRouterProvider, $locationProvider) {
        });
Myapp.run(['$route', '$http', '$rootScope', function ($route, $http, $rootScope) {
    var url = 'mydirectory/Url.json';
    httpRequest.get(url).then(function (response) {

        if (response.statusCode == 200) {

            var result = data.links;

            for (i = 0; i < result.length; i++) {
                $urlRouterProvider.when("/", {
                    templateUrl: result[i].Url
                });
            }
            $route.reload();
        }
    }, function () {
        console.log(Error!);
    });

}]);

In your application.js file, you can update the code of common_controller() and use it to dynamically update the JSON file (Url.json) with new links.

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

What is the best way to determine the width and height of text within a TextArea using JavaScript in an HTML document

Imagine this scenario: https://i.stack.imgur.com/cliKE.png I am looking to determine the size of the red box within the textarea. Specifically, I want to measure the dimensions of the text itself, not the dimensions of the entire textarea. The HTML code ...

Node.js does not allow for the usage of `.on` to monitor events until the client has been

I'm currently working on developing a WhatsApp chatbot using the whatsapp-web-js package. However, I am facing some difficulties with implementing it due to my limited knowledge in node JavaScript and async code. let client; //To establish connection ...

ensure that html tags display properly when retrieved from json in an angular directive template

Trying to embed ruby tags in a directive template but struggling with escaping them. Despite reading about $sce and filters, the confusion deepens as browser tabs multiply. The directive code is as follows: angular.module("ngFlashCard", ["ngSanitize"]).d ...

What is the best way to transfer a property-handling function to a container?

One of the main classes in my codebase is the ParentComponent export class ParentComponent extends React.Component<IParentComponentProps, any> { constructor(props: IParentComponent Props) { super(props); this.state = { shouldResetFoc ...

Tips on choosing just the selected checkbox values

In my CodeIgniter view, I am utilizing AJAX to post data to my controller. <script type="text/javascript"> $(document).ready(function(){ // find the input fields and apply the time select to them. $('#sample1 inp ...

Implement a mandatory parameter in the URL route using ui-router

My Angular routing configuration using ui-router is quite simple: $stateProvider .state("master", { abstract: true, url: "/{tenantName}" }) .state("master.home", { url: "", }) .state("master.login ...

Unable to access a user's public information using Instagram's API

I've spent the past week trying to create a simple Instagram preview application that should show a user's public data such as username, followers, following, and profile picture URL, but unfortunately, I haven't been able to find a solution ...

npm unable to locate the specified file

I'm currently following a tutorial on creating a Google Maps clone. After completing the build, I tried running the npm start command but encountered the following errors: npm ERR! code ENOENT npm ERR! syscall open npm ERR! path C:\Users\m ...

What is the correct way to add an object to a specific array in express.js?

My goal in the following function is to write a JSON file with an array of data as strings. However, the push() function, which is commented out, is causing the code to not execute as intended. Everything works fine without that line of code, but I do need ...

Creating interactive rows in a table using AngularJS

I am looking to automatically populate rows in table 2 based on the count value from table 1. Table 1 has a field called count which determines how many rows should be displayed in table 2. I am just starting out with AngularJS, so any guidance on how to ...

Passing information from the created hook to the mounted hook in VueJS

How can I transfer data from the created function to the mounted function in VueJS? In my VueJS application, the code in my created function is as follows: created: function(){ $.getJSON({ url: 'static/timeline.json', success:function( ...

Receiving unexpected results when returning a function within a React hook

I'm currently working on developing a custom React hook that will provide users with a function to execute. This hook is designed to generate a function internally. Check out this simplified example // fetch.js import { useEffect, useState} from &qu ...

Utilizing ng-click within ng-repeat along with $index

I'm experimenting with using ng-click on a div that is part of an ng-repeat loop, utilizing $index as seen in the code below : HTML: <div class="elementContainer" ng-repeat="element in elements" ng-click="elementUrl($index)"> <h2>{{ ...

Subscribe on Footer triggers automatic scrolling to the bottom of the page

Whenever I fill out the form in the footer and hit submit, it directs me to a different page while automatically scrolling back down to the footer. I'm looking for a solution that prevents this automatic scrolling. I've attempted using window.sc ...

What could be the reason my code isn't successfully performing addition within the input field?

As a novice, I am practicing by attempting to retrieve a number from a text field, prompting the user to click a button that adds 2 to that number, and then displaying the result through HTML. However, I keep encountering an issue where NaN is returned whe ...

How can I update the value of a span element that was added to the HTML document through an AJAX request?

When a modal is triggered on click, data is added to it through an AJAX request to a PHP file. After the AJAX call, I want the values in span elements within the modal to change simultaneously with the input field of the modal. I attempted this JavaScript ...

JavaScript has received an event on Server XHR

Situation: There is a scenario where the target API is external and cannot be altered. A JS client initiates sending data to the API upon clicking a button. The code snippet resembles something like this: $.ajax({ type: "POST", url: &quo ...

AngularJS: A guide on retrieving time from a date string in JSON format

Is it possible to extract a formatted time string from incoming JSON data without using moment.js in AngularJS? Sample HTML Code: <div ng-repeat="event in events | limitTo:1"> <div class="row spot"> <span class="orange">Whe ...

What is the best way to transfer a variable from PHP to JavaScript as the actual variable itself, rather than as a string?

I am transferring data from PHP to JavaScript using AJAX. I apply json_encode before sending the data. Here is an example: $data = [ [ "path" => "/TestMenu1", "component" => 'test1', "children" => [[ ...

Guide to extracting a specific segment from req.body in Node.js

I've been attempting to access a specific nested property of req.body, but the output always turns out to be undefined. Here is the code snippet: let dataReceived = JSON.stringify(req.body); console.log(dataReceived); let refCode = ...