What measures can be taken to avoid the sibling state controller from constantly refreshing?

Check out the code here

Within my main dashboard parent state, I have two child states: tags and tickers.

When a button in the tickers state is clicked, only the tags state should refresh. Currently, both states are refreshing.

https://i.sstatic.net/tP6mK.png

https://i.sstatic.net/QiJBq.png

The onInit tickersController console.log should only be executed once. However, the tagsController should run every time a ticker is clicked.


var routerApp = angular.module('routerApp', ['ui.router']);

routerApp.config(function($stateProvider, $urlRouterProvider) {

    $urlRouterProvider.otherwise('/dash');

    var dash = {
      name: 'dash',
      url: '/dash?ticker',
      params: {
        ticker: 'AAA'
      },
      views: {
        '': { templateUrl: 'dashboard.html' },
        'tagsList@dash': {
          url: '/tags',
          templateUrl: 'tags-list.html',
          controller: 'tagsController'
        },
        'tickersList@dash': {
          url: '/tickers',
          templateUrl: 'tickers-list.html',
          controller: 'tickersController'
        },
        'alertsList@dash': {
          url: '/alerts',
          templateUrl: 'alerts-list.html',
          controller: 'alertsController'
        }
      }
    };

    $stateProvider
      .state(dash);            
});

routerApp.controller('tagsController', function($scope, $state) {
    $scope.ticker = $state.params.ticker;

    function getList(ticker) {
      switch(ticker) {
          case 'AAA' : return ['aaa tag 1', 'aaa tag 2', 'aaa tag 3'];
          case 'BBB' : return ['bbb tag 1', 'bbb tag 2', 'bbb tag 3'];
          case 'CCC' : return ['ccc tag 1', 'ccc tag 2', 'ccc tag 3'];
      } 
    }

    $scope.tags = getList($state.params.ticker);

    this.$onInit = function() {
      console.log('onInit tagsController');
    };
});

routerApp.controller('tickersController', function($scope, $state) {
    $scope.changeScotchState = function(theTicker) {
        $state.go('dash', { ticker: theTicker });
    };

    $scope.tickers = [
      'AAA', 'BBB', 'CCC'
    ];

    this.$onInit = function() {
      console.log('onInit tickersController', $state.params.ticker);
    };
});

routerApp.controller('alertsController', function($scope, $state) {

    this.$onInit = function() {
      console.log('onInit alertsController', $state.params.ticker);
    };

});

Answer №1

https://plnkr.co/edit/iramGsSrJ2vKYvDPWFTb?p=preview

To prevent a view from refreshing, you must move it to one of the parent states. Below are the modified states that should resolve the issue:

    var sections = {
      name: 'dash.sections',
      url: '?sectionId',
      views: {
        'sectionsList@dash': {
          templateUrl: 'sections-list.html',
          controller: 'sectionsController'
        }
      }
    }

var dashboardState = {
  name: 'dashboard',
  url: '/dashboard',
  abstract: true,
  views: {
    '': { templateUrl: 'main-dashboard.html' },
    'sectionsList@dashboard': {
      templateUrl: 'sections-list.html',
      controller: 'sectionsController'
    }
  }
};

Answer №2

After making some adjustments, I modified your Plunker to function smoothly without needing a state refresh:

https://plnkr.co/edit/ntGVGQ06yVQC4W0Fl7A8?p=preview

Pay attention to the broadcasting section:

    $scope.changeScotchState = function(theTicker) {
   $rootScope.$broadcast('newData',  theTicker);
};

and the event handling with $on method:

   $scope.$on('newData', function(event, ticker){

      $scope.tags = getList(ticker);
      $scope.ticker = ticker;
    })

These specific parts have been significantly modified and improved.

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

App.controller attributes in HTML tags are not receiving the value of the HTML variable

In the process of developing a simple student-teacher web application, I am utilizing AngularJS to handle the front-end. Within my JavaScript file, there are two app controllers - one for fetching student data and another for retrieving subjects assigned t ...

Retrieve the Content-Type header response from the XHR request

My intention is to check the header content type and see if it is text/html or text/xml. If it is text/html, then it indicates an error that I need to address before moving forward. ...

Addressing the issue of empty ngRepeat loops

Utilizing ngRepeat to generate table rows: <tr ng-repeat="User in ReportModel.report" on-finish-render> <td><span>{{User.name}}</span></td> </tr> An on-finish-render directive triggers an event upon completion of t ...

Tips for updating the value of a key in a JavaScript object when the TextField tag's value changes

Here is the schema I am using for my model: const workoutSchema = mongoose.Schema({ workouts: [ { workoutName: String, sets: Number, reps: Number, weight: Number, }, ], }); Below is the postData referenced in the text f ...

The functionality of window.event.target appears to be malfunctioning in the Firefox browser

I have been working on an angularjs application. We have implemented a functionality to display alerts for unsaved changes using window.event.target. Everything was functioning correctly in all browsers except for <code>Firefox. The error message w ...

NG-show does not function properly with Angular validation messages when there are two input fields present

I have created a form with two modes: 'Create' and 'Edit'. Depending on the mode selected, specific div content is displayed in different areas of the layout. The content of the div includes an input field and validation messages relate ...

React - Effective Ways to Update State Following an AJAX Call

I'm currently in the process of transitioning one page within my web application from using jQuery and Vanilla JS to utilizing React. However, I'm facing some challenges as React is still relatively new to me. On this particular page, I have an ...

Invoke a JavaScript function from a dynamically inserted nested function

My primary application loads JavaScript files based on the page being visited: var MainApp = (function() { function loadPage(folder, template) { $.getScript('scripts/' + template + '.js') .done(function() { ...

Discover the route connecting two points. The current maze algorithm is operating at a sluggish

I'm in the process of developing an algorithm to identify the most efficient route between two points within a maze, but I've hit a snag with its current speed. Here's what I've done so far: Auxiliary classes: import { Coord } from " ...

Is it acceptable to assign unique names to individual arrays within a multidimensional array?

I was curious about the possibility of naming arrays within a multi-array, similar to how it can be done with individual arrays. For example: var cars = new Array(); cars[0] = "Saab"; cars[1] = "Volvo"; cars[2] = "BMW"; I was wondering if there was a way ...

Unable to show JSON data on the console

I am attempting to retrieve a large array of JSON objects from a remote server. The server-side is based on Node.js + redis. Here is my ajax query: $.ajax({ crossDomain: true, type:"GET", contentType: "application/json", url: "http://****. ...

Dynamically injecting Ace editor into an Angular 2 application

My goal is to dynamically load the ace editor into my angular2 application when a button is clicked. However, I keep encountering an error in the console that says: Error: ace.edit can't find div #editor Here's a snippet of the code I'm ...

Utilizing multiple instances of Express in Node.js

I've been struggling to grasp how the Expressjs framework for Node.js manages routes across multiple files. In my main index.js file, the setup looks something like this: var express = require('express'); var app = express(); app.use(' ...

Unable to retrieve scope variable within AJAX call

I am currently in the process of running a loop function that contains an AJAX request within it. However, I am facing difficulties with the success function on the AJAX not being able to access a counter variable outside of the loop function. var upda ...

Redirecting with PHP after registration using AJAX

My registration form incorporates PHP error checking for issues like a short password. AJAX alerts the user with any errors echoed from PHP. Once the if else statement in PHP is executed, the user is successfully registered and redirected to index.php. he ...

Exploring the possibilities of Obj file manipulation with threejs- Selection, updating, and transforming

I'm currently working on an application for 3D Visualization and Interactivity using threejs. Here are the main functionalities I aim to include in this project: In this app, users should be able to: Rotate and Scale the Object - completed Manipul ...

Is there a way to create a function in JavaScript that eliminates duplicate Objects within an Array of Objects?

Currently, I'm working on a function to store details of a couch in a JS object with 3 properties locally. The properties include: An ID (obtained from the product URL using a function) A color (retrieved through an event listener) A quantity ...

iOS 8: mysterious void found at the bottom of the Safari home screen page in full screen mode

Hello everyone, I hope you can assist me with a dilemma I am facing. Despite being a long-time reader of this forum, this is my first time posting here. I have searched extensively online for solutions to my issue but have not found anything recent or effe ...

Develop an outline using D3.js for the clipath shape

After successfully creating a shape with a color gradient, I encountered the need for further customization. If you are interested in this topic, check out these related questions: Add multi color gradient for different points in d3.js d3.js scatter plot c ...

Issue encountered with updating canvas texture twice in A-Frame and pdf.js while operating in virtual reality mode

Using the power of A-Frame and pdf.js, I embarked on a quest to build an incredible VR application for viewing PDF files. Everything seemed to be working seamlessly on my desktop - flipping through PDF pages, rendering them onto a canvas, it was a sight to ...