SignalR fails to refresh ng-view upon page change

1.- Setting up ng-route is straightforward. I have 3 buttons that navigate to different paths.

2.- There is a parent controller and a child controller for ng-view.

3.- In the ng-view template, there are spans bound to properties like subCtrl.id and 'subCtrl.something'. The initial values are set as something.id=1 and something.name='blondie'.

4.- When calling the SignalR method through Fiddler at the initial route, everything works fine as it updates the view with 'Angel Eyes'.

ISSUE: However, if I change the route by selecting option 2 or 3 and call the SignalR method via Fiddler, the client receives the update and console logs 'Angel eyes', but the view does not get updated!

HTML

<div ng-app="app">
<div ng-controller="mainCtrl as ctrl">
    <button ng-click="ctrl.optionSelected(1)">1</button>
    <button ng-click="ctrl.optionSelected(2)">2</button>
    <button ng-click="ctrl.optionSelected(3)">3</button>
    <div ng-view></div>
</div>
...

The overall code structure may seem lengthy, but the problem lies in a simple issue. Please refer to the following demonstration:

Functionality on the initial route:

https://i.sstatic.net/JpAer.gif

Failure to update after changing views:

https://i.sstatic.net/t6SQa.gif

Any insights on what could be causing this discrepancy?

Answer №1

Big thanks to Leandro Tutini for sharing this solution over on es.stackoverflow

The issue here is that only the first controller is connected to the SignalR event, causing the second controller to not function as expected.

A quick fix would be to move the SignalR definition to the base controller, allowing it to capture events and pass them down to the child controller.

app.controller('baseCtrl', ['$location', '$scope', '$rootScope', function ($location, $scope, $rootScope) {

var self = this;
self.optionSelected = function (option) {
    $location.path("/" + option);
}
self.hub = $.connection.AppHub;

self.hub.client.Hello = function () {
console.log("Hello");
$rootScope.$broadcast('UpdateName', 'Beautiful Soul');
};

$.connection.hub.start().done(function () {
    console.log('SignalR connection established');
    });
}]);


app.controller('childCtrl', ['$routeParams', '$scope', '$rootScope', function ($routeParams, $scope, $rootScope) {
var self = this;
self.something= {};
self.something.id = $routeParams.id;
self.something.name = 'Brown Eyes';

$scope.$on('UpdateName', function(name){ 
    self.something.name = name;
    $rootScope.$apply();
});

}]);

Answer №2

A helpful way to achieve this is by utilizing the $timeout directive. Simply trigger the angular events once all hub modifications have been completed.

Answer №3

Absolutely! It's essential to have SignalR functionality integrated into the main ng-controller for optimal performance.

In my personal experience with an Angular SPA WebAPI project, I encountered challenges updating my collection (view - ngRepeat) when navigating to different pages and returning. The issue was resolved once I transitioned from msgsCtrl to rootCtrl and utilized $rootScope effectively.

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

I am looking to integrate a function into an ejs page using a node.js app and express, but I need to ensure that it does not execute

I am currently developing an application in node.js, utilizing mongoose and express. My goal is to pass an asynchronous function that triggers the opening of a browser window using puppeteer to an ejs page, and execute that function only upon clicking a bu ...

Issue with Angular and Karma: HTTP GET request not running

Currently, I am working on an AngularJS project that utilizes Karma to execute some unit tests directly in the browser. To conduct these tests, I have opted for mocha as the test framework. The challenge I am facing lies in running specification tests tha ...

Refreshing the child route page does not display the specific data assigned to that particular route

I have everything set up on codesandbox. Any assistance would be highly appreciated. // Here is the link to my Axios Getter in /year methods: { async fetchData() { const self = this; const response = await axios.get( "https://e ...

Creating an Organizational chart with the use of JavaScript

From the server, I receive JSON data. In my HTML file, I am looking to showcase an organization chart in the following format: CEO | | #Manager #Manager Utili ...

What is the best way to create an onwheel event that produces an up and down effect using JavaScript?

Looking for a way to trigger a function or loop when scrolling up or down using the onwheel event. Check out the code snippet below: let demo = document.querySelector('#demo'); let c = 0; window.onwheel = function() { c ++; demo.innerHTML ...

Transform an array containing arrays into an array of individual objects

After spending a considerable amount of time trying various solutions, I am still unable to achieve the desired result. The issue lies in getting an array of objects from service calls and organizing them into a single array for data loading purposes. The ...

Generating a menu in one-hour intervals

Could someone please advise on the best approach to generate a markup like the one below using Angular: <select> <option value="0000">00:00AM</option> <option value="0100">01:00AM</option> <option value="0200" ...

Is there a way to store an SQL query within a variable and then expand upon it?

While experimenting with potential SQL injections on my database, I've encountered an issue where a simple function returns results that a user should not have access to. The return value seems to be correct based on the id, but the rest of the query ...

The Truffle test encounters an issue: "Error: Trying to execute a transaction that calls a contract function, but the recipient address ___ is not a contract address."

Every time I run truffle test in the terminal, I encounter the following error message: Error: Attempting to run a transaction which calls a contract function, but the recipient address 0x3ad2c00512808bd7fafa6dce844a583621f3df87 is not a contract address. ...

Once logged out in Vue Router, the main app template will briefly display along with the login component

After clicking the logout button, I am experiencing an issue where my main UI remains visible for a few seconds before transitioning to a blank page and displaying the login form component. This behavior is occurring within the setup of my App.vue file: & ...

Issue with Firebase Storage: Invalid character detected in the string format 'base64'

I am currently developing a project using react-native and I am facing an issue with uploading an image to Firebase using Firebase Storage. To select the image from the phone, I am utilizing react-native-image-picker, which provides me with the base64 enco ...

Leverage the power of JSON to efficiently represent a collection of string

Currently, I am engrossed in reading the 3rd edition of JavaScript Pocket Reference. The author makes an interesting statement in chapter 5 - Objects on page 75: In JavaScript, objects are dynamic, allowing properties to be added and deleted at will. Int ...

I am having trouble getting text to display properly in a jQuery Mobile dialog

I am attempting to dynamically set the header and button texts using JavaScript, but unfortunately it's not working as expected. To demonstrate the issue, I have added my code on jsfiddle: http://jsfiddle.net/tMKD3/8/. Here is the HTML code: <bod ...

Combine two pieces of data from a JSON object using Angular's ng-repeat

Trying to organize data from a separate array into one section of a table. The first JSON named "names" : [ { "name": "AAAAAA", "down": "False" }, { "name": "BBBBBB", "down": "Tru ...

Retrieving results from a Node.js application that utilizes multithreading

A new function called diversify() has been developed to execute an expensive function f() in parallel on all the cores of the machine in which it is being deployed. Additionally, a mechanism has been implemented so that when f() returns a value on one core ...

When running the `vue-cli-service test:unit` command, an error involving an "Unexpected token" message related to the usage of the spread operator

Within my code, I am utilizing the destructuring operator. However, during the module build phase, I encountered an "Unexpected token" error. Any suggestions on how to resolve this issue without completely rewriting my code to avoid using the destructuring ...

Using JavaScript to pre-select a radio button without any user interaction

Is there a way to programmatically set a radio button in a group without physically clicking on the button? I am attempting to open a jQuery page and depending on a stored value, the corresponding radio button should be selected. I have researched similar ...

Resizing Images with JavaScript

I have been attempting to create a functionality where an image enlarges itself upon a user click and reverts back to its original size when the cursor is moved away. However, I am facing difficulties as the image is not responding, it's a large 800 p ...

What is the process for including a scope in an Angular.js HTTP controller?

I am looking to access a $scope variable within this controller in order to utilize Angular functions like ng-click and ng-change in my HTML. Currently, I am only able to use the $http function but unable to execute any Angular methods on it. I am struggli ...

How to Get into a Nested Class in JavaScript

I'm struggling to articulate my question, but I know there's a solution out there. I have profile cards in HTML, each with the class "card" containing two numbers. My goal is to display a progress bar specific to the % relationship of these numbe ...