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

Arranging array positions in ThreeJS

My BufferGeometry contains an array of x/y/z positions with almost 60,000 points (18,000 values), [3, 2, 1, 3, 2, 1, 3, 2, 1, ...] To obtain random points, I am considering shuffling these positions and then selecting the first 30,000. One idea is to fir ...

What is the best way to adjust the height of an IFrame to match the size of its content?

I attempted to set the height of an IFrame to 100% (similar to setting a <div> to height:auto). I specified the height attribute in the <iframe> tag as 100% and also set the height in the style to 100%, but it doesn't appear to be functio ...

Error: Trying to access the 'title' property of an undefined variable in Vue.js

Creating a replica of hackernews by utilizing the axios API. The NewItem.vue component is not receiving any data, resulting in an error — TypeError: Cannot read property 'title' of undefined. Can you identify what's causing this issue in t ...

Using JavaScript to create customized checkboxes is a useful way to

I am looking to develop a JavaScript code that saves all the checkboxes selected by a user. When the user clicks on the finish button, the code should display what they have chosen (text within the label). Admittedly, I am unsure of how to proceed and wou ...

What is more effective: utilizing document fragments or string concatenation for adding HTML to the DOM?

My task involves adding a collection of cards to the DOM. html <div class="card"> <div class="card-title">Card 1</div> <div class="card-subtext">This is card 1</div> </div> js let ...

Encountering a Next.js error while trying to link to a dynamic page

My current folder structure is as follows: - blog (directory) -- index.js (list of all blog articles) -- [slug].js (single article) Whenever I am inside index.js, the code looks like this: const Blog = props => { const { pageProps: { articles } } = ...

Find the identifier that does not currently exist in the collection of objects

There is a situation where I have an array and an object that consists of arrays of ids, which are essentially permission objects. My goal now is to extract the ids that do not exist in the given object. Can someone assist me with devising the necessary l ...

When working with Next.js, I encountered a scenario where the useEffect() function was being triggered twice. I attempted to solve this issue by providing an empty array as the second argument, but to no

When working with Next-JS, I encountered an issue where the useEffect() function was running twice. While I heard that using an empty array as the second argument can fix this in React, it did not work in my case within Next-JS (which is based on React). ...

"Dealing with an unspecified number of fields in an ExtJS data model

I have a data model that is designed to accommodate various incoming data by keeping it generic and allowing for the addition of multiple meta data tags to my project. How can I effectively map these data fields to the Model or access them in the array w ...

Is there a way to identify the Xpath after clicking a button that adds a row to the JQGrid?

Seeking the Xpath for the Row that was added upon clicking a button. Need to click on the datepicker in the first row and first column to select a date. How can I locate the Xpath for this date picker element? See my code snippet below `<table ...

Unlimited Lunch Options and Navigational Links

Looking for help with displaying the ul for MAINTENANCE and referencing specified classes from a CSS style sheet that are working elsewhere. However, the sub menu for MAINTENANCE is not showing up. Any suggestions? /* * Superfish v1.4.8 - jQuery menu w ...

Guide on implementing ng-repeat within a nested JSON structure in your Ionic app

Struggling with implementing ng-repeat in a nested json object. { "title": "Important message 01", "img": "any url image here", "authorPhoto": "http://lorempixel.com/40/40/people/4/", "author": "John Doe", "datePos ...

Filter Observable based on object array property

I am trying to filter an Observable and only keep the stream that has a specific property value in an array of objects inside it. For example, consider this Observable: const observable = of({name: 'agency', year: '2010', job: [ ...

Understanding Node.js document object

Hey, I'm currently trying to execute a JavaScript function on the server side using node.js, but I've encountered an issue. The function relies on accessing hidden values within the returned HTML using the document DOM, however, the document obje ...

Is there a way to turn off Sequelize syncing?

I need assistance with my nodejs project where I am trying to establish a connection with mysql. The issue is that the connection is automatically creating tables based on the models defined, which is not what I want. How can I disable this automatic table ...

Discover the secrets of accessing two distinct objects returned by a single REST URL with Backbone

I am working with a REST URL that looks like this: /users/<user_id>/entities This URL returns data containing 2 objects as follows: { "players": { "test_player2": { "_id": "test_player2", "user": "f07590 ...

Guide on retrieving JSON information within an array utilizing a loop function

Hey everyone, I'm facing an issue and I could really use some help. I'm new to working with ajax processing and I'm stuck on a problem. I have successfully retrieved ajax data and now I need to store it in an array. My goal is to populate a ...

What is the best way to conceal the initial column using jquery?

Is there a way to automatically hide the first column of data as it loads from a csv file using jquery and AJAX? I know you can do this using onclick function, but I prefer to have it automatically hidden. How can I achieve this? Below is the sample CSV d ...

Limit the precision of decimal number output to a specific value

I need assistance with achieving the output 999999.35 in angular or javascript combined with html. I am looking to restrict the number of 9's to a maximum of 6 digits before the decimal point, and after 6 digits it should not accept any more digits. A ...

Utilizing jQuery UI autocomplete with AJAX and JSON data sources

I've been facing an issue with the jQuery UI autocomplete feature, and despite extensive research, I have only managed to partially resolve it. The code below is what I'm currently using to make it work: $("#term").autocomplete({ source: fun ...