Refresh the recently added body element in a document - Anglular

Upon logging in with the correct credentials, the server responds with a string containing new elements that include scripts. This element set replaces the content of the login page body. However, after loading the new content, the Angular functions fail to work properly.

Below is the login page:

<!DOCTYPE html>
    <html>
        <head>
        </head>
        <body ng-app="loginApp">
            <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
            <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.6.4/angular.min.js"></script>
            <script type="text/javascript" src="js/login/loginMain.js">
            </script>
            Login<br><br>
            <form ng-controller="loginController" ng-submit="postForm()">
                User Name:<br>
                <input ng-model="unameInputField" type="text" name="user[name]"><br>
                Password:<br>
                <input ng-model="passwordInputField" type="password" name="user[password]">
                <input type="submit" name="Submit">
            </form>
        </body>
    </html>

And here's the code from loginMain.js:

/* public/js/controllers/apps *************************************/
angular.module("loginApp", []); 

angular.module("loginApp").controller("loginController", function($scope, $http){
    $scope.unameInputField = "";
    $scope.passwordInputField = "";
    $scope.postForm = function() {
        $http.post("/credentials.json", {username: $scope.unameInputField, password: $scope.passwordInputField},
         {headers: {'Content-Type': 'application/json'}}).then(
                function(res) { //Success
                    // window.location.href = 'http://localhost:3000/home';
                    console.log(res.data)
                    $("body").attr("ng-app", "myApp");
                    $("body").html(res.data);
                },
                function(res) { // Failed
                    alert("POST FAILED, Server is most probably offline")
                }
            )
    }
}) 

Here are the HTML elements intended to be placed inside the body tag:

    <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
    <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.6.4/angular.min.js"></script>
    <script type="text/javascript" src="js/main.js"></script>
    <title>Home Electricity Manager </title>    
    <h1 id="the-header">Welcome to home electricity manager <a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="0a786b6e6579666b7c246124676b786364657c4a6d676b636624696567">[email protected]</a>!</h1>
    <div id="button-1-div" ng-controller="myController" order="1" style="text-align: center; display: inline-block;" ng-init="spanText=S4555">
        <span id="button-1-span-1" ng-click="changeText()" style="white-space:pre;">{{spanText}}</span><br>
        <button id="butt-1" ng-style="myStyle" ng-click="toggleRelay()">{{ButtonStatus}}</button>
    </div><br>
    <div id="button-2-div" ng-controller="myController" style="text-align: center; display: inline-block;"> 
        <span id="button-2-span-2" ng-click="changeText()" style="white-space:pre;">{{spanText}}</span><br>
        <button id="butt-2" ng-style="myStyle" ng-click="toggleRelay()">{{ButtonStatus}}</button>
    </div><br>
    <div change-cred></div>

In Chrome Developer View, it appears that the content has been replaced correctly, but the user view shows that Angular fails to compile the new content. Here's an image of how the page looks:

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

If the Angular functions were functioning as expected, the user page would appear like this:

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

I apologize for any shortcomings in my English expression. I hope you understand the issue at hand!

Answer №1

First and foremost, I strongly urge you not to pursue this idea. Attempting to reinvent the wheel when Angular routing already offers a solution will only make things more complicated in the long run. Take some time to study the principles behind views and familiarize yourself with either AngularJS's default routing system or the more advanced UI-Router module. This investment in learning will prevent headaches down the line. Creating a "login" state that redirects your app when the user is not logged in can be easily achieved through AngularJS routing, with plenty of examples available.

In regards to your original question, it appears that the outcome you are experiencing is to be expected. It seems that dynamically adding HTML elements to the body interferes with the initialization of your second AngularJS app (presumably defined in main.js), causing it to not properly recognize the current page content. Consequently, the initial compilation phase fails to work as intended, resulting in an HTML page that is not correctly bound to the current scope.

If a similar solution is truly necessary, I would suggest two actions:

  • Include feedback such as alert() or console.log() statements in the main.js file to verify its execution.
  • Attempt to manually compile the "view." AngularJS provides a $compile method that could serve this purpose, although implementing it successfully in your scenario may prove challenging (personally, I have only utilized $compile within custom directives for processing dynamic DOM changes induced by a jQuery plugin).

I hope this clarifies matters somewhat. Nonetheless, I reiterate my advice to refrain from pursuing this approach and instead utilize UI-Router for a more efficient solution.

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

Avoiding page refresh when clicking on a button component in React

Apologies if this question has already been addressed. I've done my research but I might be missing something. Currently, I'm working on a React app and I want to ensure that my buttons do not reload the page, but only refresh the state. Here&ap ...

Creating a program to ascertain whether two integers inputted by a user are odd numbers

I need assistance in creating a function that can ascertain whether two numbers input by the user are odd and then return a boolean value that is true only if both numbers are odd. I'm already familiar with creating a function to check for even number ...

Removing a value from an array contained within an object

I have a scenario in my task management application where I want to remove completed tasks from the MongoDB database when a logged-in user marks them as done. Below is the snippet of code for my Schema. const user = new mongoose.Schema({ username : Str ...

Leveraging AJAX responses to reduce additional requests in single-page applications

I am currently developing an ecommerce app using the MEAN stack and have encountered a recurring question regarding AJAX http requests. The single-page architecture integral to MEAN makes this question particularly significant. I have come across advice s ...

HTML drag-and-drop setDragImage fails to show ghost image on initial drag operation

Currently, I am working on developing a drag and drop menu feature that allows users to drag an image thumbnail from one div to a canvas element. The main issue I am facing is that the source div uses a sprite for displaying its background thumbnail. As a ...

Tips for preventing the collapse of a table row using a button?

I have implemented a Bootstrap collapse feature on my table row. Currently, the collapse can be triggered by clicking anywhere on the row, which is working as intended. However, I would like to make one exception - if the user clicks on the desktop icon i ...

Having trouble parsing dates in Javascript?

let date = new Date("2017-09-12T12:00:00"); console.log(date.getUTCMonth()); Surprisingly, the code logs 08 instead of 09, even though year, day, hour, and minute are parsed correctly. What could be causing this discrepancy? Is there a way to extract 09 ...

What is the best way to incorporate a custom string into an Angular application URL without disrupting its regular operation?

In my Angular application with angular ui-router, I am facing an issue with the URL structure. When I access the application from the server, the URL looks like localhost/..../index.html. Once I click on a state, the URL changes to localhost/.../index.htm ...

ui-sref behaving unexpectedly in nested view components

I have completed my homework by reviewing nearly 9 UI-sref related questions on various platforms, yet I can't seem to figure out why my code is not functioning as expected. After spending hours debugging the app, the issue remains elusive. My webpag ...

Confusion arises between Bootstrap button plugin and Vue checkbox click event

After incorporating bootstrap.min.js into my Vue app, I noticed that the checkboxes' @click event is no longer triggered. This issue specifically occurs when using bootstrap's button-group with data-toggle="buttons". If I remove bootstrap.min.js, ...

Socket.IO client's socket.id updating without requiring a reconnect

In the process of creating an application, I encountered a situation where I needed to map sockets to some object. To achieve this, I relied on the socket.id variable provided by Socket.IO. However, during debugging, I discovered that the socket.id was cha ...

Vercel offers unique functionality specifically designed for Next.js

As part of my application migration process, I am transitioning to the nextjs framework. I am curious if all the features and functionalities offered by Next.js can be replicated on private Docker servers or other Jamstack platforms, or if there are limi ...

Leveraging a nodejs script integrated with socket.io within an angular/electron hybrid application

I have successfully created an electron/angular app that is functioning well. Additionally, I have developed a nodejs script to open a socket.io server using typescript + webpack to generate all files in a bundled js file. My challenge arises when trying ...

Steps for incorporating monaco-editor into a website without utilizing nodejs and electron

Currently, I am working on building a basic web editor and came across Monaco-editor. I noticed someone using it with Electron, but I am interested in integrating it into plain JavaScript just like on their webpage (link). However, I am struggling to fin ...

What could be the reason for e.target.value being undefined?

Can someone explain why e.target.value is returning undefined when logged to the console in this simple component? The value should be defined within the element, so I'm confused as to why e.target is not giving the correct value. const NavBar = () = ...

Is it possible to input a parameter into a resource without modifying the route?

Essentially, I am attempting to pass a parameter from my Angular app to my NodeJS service. The GET request in question looks like this: resource: $resource(nodeRoute + '/test'. {}, { query: { method: 'GET', ...

Diverse Range of Exports Available in React Component Library

I have been working on developing a component library consisting of multiple independent components. My objective is to enable users to easily import and use these components in their projects, similar to the following: import One from 'component-lib ...

Retrieving JSON data every few seconds using JavaScript

I am attempting to continuously read a local JSON file in order to generate a plot. This JSON file is updated every n seconds. To accommodate for the changing file, I am using a combination of $.getJSON() and setInterval() to read the file at regular inter ...

Move the Form to the Top of the Window and Highlight the First Input Field

There's a link in the header that says "Let's chat": <div class="letstalk"> <a href="javascript:scrollForm();"> Let's chat <img src="/wp-content/uploads/link-icon.png"> </a> </div> ...

"Converting to Typescript resulted in the absence of a default export in the module

I converted the JavaScript code to TypeScript and encountered an issue: The module has no default export I tried importing using curly braces and exporting with module.exports, but neither solution worked. contactController.ts const contacts: String[ ...