How can you define a variable within the .config service in Angular JS?

Here is the code snippet I have been working on:

spa.factory("linkFactory", function() {
    var linkFactoryObject = {};
    linkFactoryObject.currentLink = "home";
    return linkFactoryObject;
});

This piece of code essentially serves as a global variable that allows me to set and read values between different controllers. It specifically helps in determining which link should be marked as active.

While my code functions effectively, there is a minor issue I encountered. If an initial value is not set in the factory when someone first enters my webpage, the 'home' link will not be set as active. On the other hand, if I do set an initial value, upon refreshing the page, the value resets to the original one, causing the home link to appear as active even though the user may be on a different page.

In an attempt to tackle this challenge, I explored using $location.path() to retrieve the path and create a function based on that value. However, due to its static nature, $location.path() proved ineffective for this purpose.

Furthermore, the route snippet below dictates the content loading process:

spa.config(function($routeProvider, $locationProvider) {
    $routeProvider
            .when('/home', {
                templateUrl: '/partials/home.html'
            })
            .when('/about', {
                templateUrl: '/partials/about.html'
            })
            .when('/skills', {
                templateUrl: '/partials/skills.html'
            })
            .when('/experience', {
                templateUrl: '/partials/experience.html'
            })
            .when('/resume', {
                templateUrl: '/partials/resume.html'
            })
            .when('/contact', {
                templateUrl:  `/partials/contact.html'
            })
            .otherwise({
                redirectTo: '/home'
            });
});

If there was a way for me to establish a variable within this section that can be accessed in my controllers, it would solve my dilemma. Unfortunately, I am unsure how to go about achieving this. Any suggestions or guidance on how to accomplish this would be greatly appreciated.

Can anyone provide insight on how I could address this challenge?

Answer №1

Give this a try. It will update the URL of the route every time the state changes.

spa.service("linkService", function() {
        var linkServiceObject = {};
        linkServiceObject.currentLink = "home";
        linkServiceObject.setRoute = function(route) 
        {
          linkServiceObject.currentLink = route;
        };
        return linkServiceObject;
    });

    spa.run(['linkService','$rootScope',function(linkService,$rootScope) {
      $rootScope.$on('$stateChangeStart', function(event, next, current) {
        linkService.setRoute(next.$$route.originalPath);
      });
    });

Answer №2

Instead of using the $routeChangeStart event, you can simplify by setting a default controller. This eliminates the need for separate controllers for each page. Within the controller, assign the current link value.

A better approach would be to create a scope variable for tracking and applying the appropriate classes to the links.

For further information, refer to the following discussion:

How to highlight the active menu item?

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

The proper method for developing Vue components that are dependent on the parent build tools

In my experience, this issue might also arise in other frameworks with plugin/component ecosystems that rely on specific build tools (such as React components with JSX). While Vue serves as my use-case. Having developed numerous Vue components as single . ...

What is the correct way to invoke a static TypeScript class function in JavaScript?

Recently, I encountered a scenario where I have a TypeScript script called test.ts structured like this: class Foo { public static bar() { console.log("test"); } } The requirement was to call this TypeScript function from plain JavaScript ...

Following the submission of the ajax form, the page is reloading unexpectedly

I need the voting form on index.php to submit without refreshing the page and display results from an external page within index.php. HTML <head> <script src="http://ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script&g ...

What is the best way to retrieve both the start and end date values from a React date range picker component

I have integrated a date range picker npm package called react-date-range into my code. On my screen, there is an "Apply Dates" button. When this button is clicked, I want to retrieve the selected date range value. How can I achieve this onclick event? ...

The text sliding feature gradually moves further away from the left side with each iteration

I am in the process of transferring an existing slider from one website to another. Instead of creating a text slider from scratch, I decided to modify the code I found for the new site. However, the slider is not functioning correctly on the new site. Th ...

How do you incorporate ScrollTop animations using @angular/animations?

I'm attempting to recreate the animation showcased on Material.io: https://i.stack.imgur.com/OUTdL.gif It's relatively easy to animate just the height when clicking on the first card in the example above. The challenge arises when you click on ...

Tips for enhancing the contents of a single card within a react-bootstrap accordion

Currently, I am facing an issue with my columns expanding all cards at once when utilizing react-bootstrap accordion. My goal is to have each card expand individually upon clicking on its respective link. However, I am encountering difficulties in implem ...

Combine an array of objects into a regular object

Imagine having an array structure as shown below: const student = [ { firstName: 'Partho', Lastname: 'Das' }, { firstName: 'Bapon', Lastname: 'Sarkar' } ]; const profile = [ { education: 'SWE', profe ...

Eliminate the presence of core-js in the nextjs bundle

Currently, I am tackling the challenge of minimizing bundle sizes in my Next.js project. One particular aspect that caught my attention is the inclusion of a core-js bundle for polyfills. This adds an extra 50KB to the size of the main bundle, which I aim ...

How can Angular be used to trigger a batch request in an Asp.Net Web API 2.0?

I have recently developed a sample web API using Asp.Net Web API 2.0 that includes Http batch support. Check out this link for more details on the example. Can anyone guide me on how to call this batch API using Angular? ...

Enhance Your Webpage with jQuery Drag and Drop Feature Across Multiple Lists

I've been successfully using "jQuery UI Sortable connectwith" for drag & drop functionality, as shown in the example here: . However, I now need to implement drag & drop with multiple UI elements and it's not functioning correctly. Example: < ...

Arranging items in ng-options through the use of orderBy

Here is the code I am struggling with: <select ng-model="i.br" ng-options="item.name as info[item.name] for item in e.br | orderBy:info[item.name]" class="combobox"> Unfortunately, the orderBy function is not sorting the options according to info[i ...

When using AngularJS, the attribute type does not display properly if it is set to "text"

In my AngularJs application, I've encountered a peculiar issue related to rendering input fields with the type "text". Strangely, every time I try to include an input with type text, the type attribute seems to magically disappear. For instance: < ...

`Generating an ever-changing masonry layout on a website using live data`

I'm currently working on a new web project and I want to incorporate a masonry view for the images on the homepage. The plan is to host this project on Azure, using blob storage for all the images. My idea is to organize the images for the masonry vi ...

Substituting text in a document by utilizing two separate arrays: one holding the original text to be found and another storing the corresponding text for

I am facing a challenge with replacing specific text strings in a file. I have two arrays - one containing the strings that need to be located and replaced, and the other containing the replacement strings. fs.readFile("./fileName.L5X", "utf8", function( ...

Create a dynamic sitemap for a Laravel website that includes variables in the slugs

My Laravel-based website features URLs like this- xyz.com/search/{id}/{name} These URLs have two variables, allowing for multiple variations such as: xyz.com/search/1/katy xyz.com/search/2/john With potentially thousands of such URLs, I need to creat ...

Ways to expand the dimensions of a Popup while including text

I am using a bootstrap modal popup that contains a Treeview control in the body. The issue arises when the node's text width exceeds the popup's width, causing the text to overflow outside of the popup. Is there a way to dynamically adjust the ...

Is it recommended to utilize CDN in Vue.js for optimal performance?

Currently facing a version compatibility issue between leaflet and leaflet-draw in my vuejs project. In light of this, I am seeking alternative solutions for map function editing such as adding polylines, copy and paste functions, and more. While I did com ...

Having trouble retrieving data using a custom URL in Axios with ReactJs

My knowledge of Reactjs is still new and I am currently working on a project using nextjs. I have a component called Trending.js that successfully fetches data from the URL "https://jsonplaceholder.typicode.com/users". However, when I try to change the U ...

Looking to display information in a column-by-column format using ng-grid within Angular JS

The data I have is structured like this: $scope.myStudentData = {"Moroni":{"id":"1","grade":"A"},"Tiancum":{"id":"2","grade":"B"}} However, the grid requires a different format: $scope.myGridOptions = [{"details":"id", "Moroni":"1", "Tiancum":"2"},{"det ...