Revamp your AngularJS controller for a fresh new look

How can a controller be refreshed in Angular? Take into account the scenario below:

<div ng-controller="MsgCtrl" ng-repeat="m in messages">{{m}}<br></div>
<script>
var ws = new WebSocket(something, something);
function MsgCtrl($scope) {
    $scope.messages = [];
    ws.onmessage = function(e) {
        $scope.$apply(function() {
            $scope.messages.push(e.data);
        });
    }
}
</script>

If the websocket connection fails, or needs to be restarted for any reason, a new websocket must be created and listened to. Is there a way to trigger the controller to run again, creating a new listener to push messages from the new connection into $scope?

In addition, as a follow-up question: Where is a reliable source to expand knowledge on Angular? The documentation on the official site may not provide clear guidance.

Answer №1

When there is a connection failure or the need to restart for any reason, it is important to reconnect the web socket. However, simply restarting the controller may not be the best approach.

Instead, I recommend creating a dedicated "web socket" service that can handle its own logic, such as reconnecting when needed. This way, the controller can focus on managing the model and view binding without getting bogged down with socket handling.

<html ng-app="MyApp">
....
<div ng-controller="MsgCtrl" ng-repeat="m in messages">{{m}}<br></div>
</html>
<script>

    var myApp = angular.module("MyApp",[]);
    myApp.factory("WebSocket",function(){
        var ws;
        var triedTime=0;
        var maxRetryTime=20;
        return {
            createWS: function(server,protocol,handler){
                ws = new WebSocket(server, protocol);
                ws.onmessage = handler;
                ws.onerror = function(e){
                    this.restartWS(server,protocol,handler);
                }
            },
            closeWS: function(){
                if(ws) ws.close();
            },
            restartWS: function(server,protocol,handler){
                if(triedTime<=maxRetryTime){
                    this.closeWS();
                    this.createWS(server,protocol);
                    triedTime++;
                }
            }
        };
    });

    function MsgCtrl($scope, WebSocket){
        $scope.messages = [];

        WebSocket.createWS("something","something",$scope.msgHandler);

        $scope.msgHandler = function(e){
            $scope.$apply(function() {
                //model update
                $scope.messages.push(e.data);

                var msg = JSON.parse(e.data);

                switch(msg.cmd)
                {
                    case "restart":
                    WebSocket.restartWS("something","something",$scope.msgHandler);
                    break;
                }
            });
        }

    }
</script>

In this scenario, the web socket will automatically attempt to reconnect upon receiving a "restart" message or encountering a connection issue. Hopefully, this solution proves useful for your needs.

Answer №2

  1. If you encounter issues, a simple solution is attempting to reload the page using $route.reload(). An even better approach is to reinitiate the websocket on the onerror.

  2. In my experience, the most beneficial platform for learning angularJS is Egghead. Additionally, stackoverflow serves as an excellent resource to seek clarification when needed.

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

Selective Box Data Update Failure in Http Service

Within the Angular service, this.set_opportunity is a crucial function: calculator_app.service('FillOpportunity', function () { this.fill_opportunity = function (path,$scope,$http) { $http.get($scope.servername + 'calculator/ge ...

Looking to dynamically generate HTML tags using jQuery and JSON?

Looking for help with inserting HTML code into a div using jQuery. <div id="addme"></div> Here is some HTML with PHP: <div class="col-md-4 product secondproduct"> <div class="images1"> <a href="<?php echo base_u ...

What steps should I take to ensure axios is returning the appropriate buffer type?

Upon initially posting this question, I was completely lost on where to even begin or how to appropriately title it. With the assistance of multiple comments, I enhanced the data provided and finally settled on the current question title - a big thank you ...

The function cannot be applied to the size of the map within the action payload

Is there a way to replace the for loop with the map method? The data structure for book.pages is in the format [{},{},{}] I tried using the size method and included this line console.log("book.pages.map.size();--->", book.pages.map.si ...

A step-by-step guide on integrating PDF.js with Vue 3 and accessing the distribution folder locally

I must clarify that I am restricted from using any vue libraries to preview PDFs; only pure pdf.js and vue 3 are permitted. Utilizing pdf.js for presenting PDF files within my vue 3 project. Inquiring about the ideal folder structure for the project to en ...

How to incorporate material-ui tabs in nextjs framework?

I'm currently working on a project using material-ui, nextjs, and typescript. My main focus right now is getting the navbar to function properly within nextjs: import * as React from 'react'; import AppBar from '@material-ui/core/A ...

Utilize AJAX to dynamically refresh the page without having to reload it, enabling the use of both POST and GET methods

In order to avoid reloading the page when refreshing, I am utilizing Ajax for this particular 3-sided content along with JavaScript. Here is the code: Content: <ul id="nav"> <li><a href="ajax_adat.php?id=8&epul=0">Data</a>< ...

Running Applications with React Using Command Line Interface (CMD)

I'm currently working on creating a .cmd file to handle the installation of dependencies and then execute my React application. Following some research, I have come up with the following code snippet inside my .cmd file: @echo off npm install pause np ...

Tips on preserving type safety after compiling TypeScript to JavaScript

TS code : function myFunction(value:number) { console.log(value); } JS code, post-compilation: function myFunction(value) { console.log(value); } Are there methods to uphold type safety even after the conversion from TypeScript to JavaScript? ...

Activating Dynamic Functionality through JavaScript Input

I am currently working on a form in Apex 4.1 where I have an address lookup field that utilizes JavaScript to connect to an address database and populate separate fields with the address details (address1, address2, town, postcode). On the same page, I ha ...

Sinon's fakeTimers failing to trigger

I'm encountering an issue with sinon's fakeTimers while working in a setup that includes Marionette.js, underscore, and chai test runner. Strangely, when I place a breakpoint in Chrome and step through the code, my timer functions as expected. Ho ...

Display only distinct dates in the ng-repeat list

I'm trying to display an unordered list created using ng-repeat. Each list item includes a month header and a blog post. I'm struggling to find a clean solution to only show one instance of each month name without resorting to complex jQuery hac ...

Why does console.log in JavaScript exhibit different behaviors as evidenced by the code?

Exploring the behavior of console.log(obj) compared to console.log("obj"+"\n"+obj) in the code snippet below reveals two distinct output outcomes. const obj = new Object() obj.first = 'John' obj.last = 'Doe' obj.alive = true ob ...

What are some ways to utilize symbol fonts such as marvosym within a web browser?

Are you looking to use special LaTeX fonts like \Pluto from marvosym in your web development projects? Wondering how to display this symbol with HTML / JavaScript / CSS without relying on an image? You can download the font from This symbol corresp ...

Does having an excessive amount of variable declarations result in a noticeable decline in performance?

One thing I notice for the sake of readability is that I tend to create new variables for data that I already have on hand. I'm curious, does this impact performance significantly? Here's an example of what I mean: const isAdult = this.data.per ...

Developing a website using custom modules in Node.js and Express framework

I am currently encountering an issue when using a custom module within one of my route functions in Express with node. Below is my current setup: In the app.js file, I require the module as follows: c_controller = require( './core/c_controller' ...

Troubleshooting tips for optimizing Opera and Internet Explorer performance

I'm currently on the hunt for solutions or techniques to debug my jquery script specifically under the Opera/IE browser. It appears that the ajax $.post() request is either not being sent at all, or it's being sent to the wrong address, among oth ...

I am developing a quiz application using JavaScript, and I am wondering how I can smoothly transition from one question to the

I'm working on developing a quiz application and I'm facing an issue where my quiz is skipping question 2 when moving from one question to the next using the "next" button. I have a total of 3 questions in my quiz and for some reason, it jumps fr ...

Unable to get the code for automatically refreshing a DIV every 5 seconds to function properly

My Inquiry Regarding DIV Refresh I am having issues with the code below that is supposed to automatically refresh the DIV id refreshDiv every 5 seconds, but it is not working as expected. <div id ="refreshDiv" class="span2" style="text-align:left;"&g ...

Enhance the current model in backbone.js by incorporating additional data

When a user selects an item on the webpage, more details need to be fetched and displayed. The API function /api/full_details has been implemented to return the additional data for that item. Challenge: How can I retrieve the additional data and append it ...