Tips for avoiding $state refresh in Components unaffected by changes to $state.var?

We are currently utilizing Angular-ui-router for managing the state of our application.

One issue we are facing is that every component refreshes when there is a change in the $state, even if it's a variable that has been updated and is not used or doesn't exist in some components.

For instance, we have a TickersPanel and a TagsPanel. When a Ticker is selected, the TagsPanel should be refreshed; however, when a tag is chosen in the TagsPanel, the TickersPanel should NOT refresh but it currently does.

I've discovered that using { notify: false } as another object can resolve this issue. However, implementing this causes NO components to refresh at all.

const save = (tag, terms) => {
    CONTAINER.push(tag);
    $state.go('charting', Term.write(terms), { notify: false }).then((stateResult) => {
        console.log('stateResult', stateResult);
    });
};

Has anyone managed to find a workaround for this problem?


TagsPanel $onInit (Executes with every $state change)

this.$onInit = () => {
    tagsCol.addEventListener('scroll', scrollingTags);

    this.tags = [];
    this.limit = 30;

    const panelOpen = Dashboard.panelStatus(this.tagsOpen, this.chartMax);
    panelOpen ? buildTagList() : collapsePanel();
};

TickersPanel $onInit (Executes with every $state change, but should only run if $state.params.ticker hasn't changed)

this.$onInit = () => {
    this.tickers = [];

    this.spy = {
        longname: "SPDR S&P 500",
        ticker: "SPY",
    };

    this.showTickersPanel = Dashboard.panelStatus(this.tagsOpen, this.chartMax);
    // const currentState = $state.params;
    // const prevState = Dashboard.getPreviousState();
    loadTickers().then(() => this.loadingTickersDone = true);
};

Answer №1

I have created a JsFiddle to demonstrate a solution that addresses the query presented in your question using uiRouter.

Within the fiddle, I have utilized state inheritance and named views to specifically reinitialize the tags state when there are changes to the tickers param.

[..]
// Utilizing @ on the view names to reference the absolute uiViews.
$stateProvider.state('tickers', {
    url: "",
    views: {
      'tickersPanel@': {
        template: [..]
        bindToController: true,
        controllerAs: "$ctrl",
        controller: function() {
          this.$onInit = function() {
            console.info('Tickers Panel $onInit');
            this.tickers = ["Ticker1", "Ticker2", "Ticker3"]
          }
        }
      },
      [..]
    }
});
$stateProvider.state('tags', {
    parent: 'tickers',
    url: "/:ticker",
    views: {
      'tagsPanel@': {
        template: [..]
        controllerAs: '$ctrl',
        bindToController: true,
        controller: function($stateParams) {
          this.$onInit = function() {
            console.info('Tags Panel 2 $onInit');
            this.ticker = $stateParams["ticker"];
          }
        }
      }
    }
});
[..]

Answer №2

Have you considered keeping track of the state within your component and simply returning early in the function if there have been no changes to the state?

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

Steps to verify if a value is an integer:

Lately, I've been working on a "spinner" that increments and decrements a number by 1 each time. However, I'm struggling to add validation to the program so that it only accepts integers (no decimals). I've tried looking into NaN and parseVa ...

Implementing a unique sorting algorithm for an array of numbers in Angular

I need to organize an array of numbers in descending order with a custom sorting method based on a specified number, all without splitting or filtering the array. I am currently working with Angular 17 and Rxjs 7.8. For instance, if I have this array of n ...

Utilizing Selenium for the Upload of an APK Document

I've encountered an issue during my test. I'm attempting to upload an APK file, but the process seems to halt at that stage. My attempts with simple sendKeys using the file path and an AutoIT script have both proven unsuccessful. Below is my in ...

What strategies can be used to effectively structure CSS and JavaScript in a project for optimal organization?

In my NetBeans project, I currently have a large web project with CSS files included in the header. Some CSS codes are needed on all pages, while others are only necessary for specific pages. I am looking to optimize high-traffic pages by removing any ...

What is the best way to eliminate all padding from a bootstrap toast notification?

I'm attempting to display a bootstrap alert message as an overlay toast (so it automatically disappears and appears above other elements). Issue: I am encountering a gap at the bottom of the toast and struggling to remove it: https://jsfiddle.net/der ...

"Encountering an error retrieving weather forecast API in JavaScript - issue with

I've been attempting to fetch the weather forecast API JSON in a similar manner to how I accessed the current weather API, but unfortunately, it doesn't seem to be working no matter what approach I take. let inOneDay = { fetchWeather: functio ...

Wcf Service does not define Angular JS methods

I am utilizing a WCF Service within an AngularJS application. The WCF Service is functional, and I am attempting to display a list of user records from a SQL database. However, upon running the application, I encountered the following errors: angular.js: ...

Ways to retrieve slider value when button is clicked?

I am currently working on a range-slider that has two ranges and I need to retrieve the slider value in my javascript code. Here is my approach so far: <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.cs ...

Updating the value of AngularJS scope from a global variable

I have a global variable called HasNewMessage, which is responsible for fetching information from the server every 3 minutes to check for new messages. I now need to access the value of this variable within one of my AngularJS applications. Here is my dir ...

Comparing strings with if-else statement

I am having trouble comparing strings in this array. For some reason, the strings are never equal. var person = ["Sam", "John", "Mary", "Liz"]; var searchedName = prompt("Enter name"); var resultMessage = ""; for (index in person) { var currentName = ...

Undefined value is returned for Vue 3 object property

Is there a way to extract additional attributes from the Keycloak object ? Currently, If I try, console.log(keycloak) it will display the entire keycloak object. Even after reloading, it remains in the console. However, when I do, console.log(keycloak.t ...

Checking if a date is before another date in MomentJS without considering the

Recently, I've been utilizing momentJS to identify future dates without a specific day. Below is the code I've been working with along with the outcome: moment('09/2010').isBefore(moment().format('MM/YYYY'), 'day') ...

Integrating AngularJS code into dynamically generated HTML using JavaScript

I am currently utilizing an outdated version of AngularJS (1.3). I have a page where I need to dynamically display different content based on database values. If the user interacts with the page and changes the database value, I want the displayed content ...

Splitting a td tag into multiple columns dynamically with Angular

I am attempting to dynamically split the table element into separate columns. My desired layout should resemble this: https://i.sstatic.net/C81tg.png The values for name and surname are fixed at 1, but the values for subjects and grades can vary (there ma ...

How to Handle an Empty Route with a Trailing Slash in Backbone Routing?

While I am aware of the potential SEO issues that come with duplicate content, my project is not currently focused on that aspect. Looking at my backbone router configuration, here it is: routes: { "": "startOrder", "order/:orderNumber/:stepName" ...

Do we really need TypeScript project references when transpiling with Babel in an Electron project using Webpack?

Currently, I am in the process of setting up my project configuration and have not encountered any errors so far. However, based on my understanding of the Typescript documentation... It appears that Project references are not essential when using babel-l ...

Dealing with AngularJS ng-model problems when duplicating a form

Currently, I am facing an issue with sending parameters to control and require some guidance. I have multiple types of questions within the ng-repeat loop named 'question' that I am iterating through. The problem arises when there are two questi ...

Tips for incorporating JavaScript into .ascx pages

What are some ways to incorporate javascript in .ascx files? ...

Is it possible to create tags in Material UI Autocomplete using events other than just pressing the 'Enter' key?

In my current project, I am utilizing the freesolo Autocomplete feature. My specific requirement is to create tags when input text is followed by commas or spaces. Currently, tags are created on the Enter event by Autocomplete, but I am looking for a way t ...

What is preventing Node.js from executing my JavaScript code in the terminal?

https://i.sstatic.net/JJmg2.jpg I need help understanding why my JavaScript code isn't working properly. Can someone explain the Uncaught SyntaxError: Unexpected Identifier error message? ...