What could be causing the old value to persist in angular $scope and not get removed

In my controller, I have defined the following:

angular.module('publicApp')
  .controller('URLSummaryCtrl', function ($scope, $location, Article, $rootScope, $timeout) {
    $scope._url = "";
    $scope._title = "";
    $scope._article = "";
    $scope._authors = "";
    $scope._highlights = [];
    $scope._docType = "";

    $scope.summarizeURL = function(){

        Article.getArticleInfo($scope.url, "").then(
            function(data){
                
                // Populate variables with data from API response
                $scope._url = data.url;
                $scope._title = data.title;
                $scope._authors = data.authors.join(', ');
                $scope._highlights = data.highlights;
                $scope._docType = data.documentType;

                if($scope._docType == 'html'){
                    $scope._article = data.article[0].article;
                }
                else{
                    $scope._article = data.article;
                }

                var _highlights = [];
                $scope._highlights.forEach(function (obj) {
                    _highlights.push(obj.sentence);
                });
                
                // Wait for article text to render, then apply highlighting
                $timeout(function () {
                    $('#article').highlight(_highlights, { element: 'em', className: 'highlighted' });
                }, 200);
            }
        );
    }

The corresponding view is as follows:

<form role="form" ng-submit="summarizeURL()">
    <div class="form-group">
      <input id="url" ng-model="url" class="form-control" placeholder="Enter URL" required>
    </div>
    <button class="btn btn-success" type="submit">Summarize</button>
  </form>

<div class="col-lg-8">
  <h2>{{ _title }}</h2>
  <p> <b>Source: </b> <a href="{{_url}}" target="_blank">{{_url}}</a></p>
  <p> <b>Author: </b> {{_authors}} </p>
  <p> <b>Article: </b><p id="article">{{_article}}</p></p>
</div>

After entering a new URL in the input field and clicking "Summarize", all values update correctly except for $scope._article. The old value remains displayed alongside the new one. Why is this happening?

EDIT #1: After further investigation, I discovered that removing the $timeout(function(){...}) section resolves the issue. So now the question shifts to why $scope._article retains the old value and appends the new one.

EDIT #2: Upon testing, I found that changing the code snippet within $timeout(...) does not affect the behavior. Even without the timeout, the problem persists. It seems related to altering the $scope._article contents, specifically adding highlights using

<em class='highlighted'> ... </em>
.

EDIT #3: Attempting to remove the added HTML before fetching new data did not resolve the issue. Here's the unsuccessful approach:

angular.module('publicApp')
  .controller('URLSummaryCtrl', function ($scope, $location, Article, $rootScope, $timeout) {
    $scope._url = "";
    $scope._title = "";
    $scope._article = "";
    $scope._authors = "";
    $scope._highlights = [];
    $scope._docType = "";

    $scope.summarizeURL = function(){
        //Attempt to remove added HTML before making new request
        $('.highlighted').contents().unwrap();

        Article.getArticleInfo($scope.url, "").then(
            function(data){ ... }
        );

Answer №1

Dealing with Jquery in angular controllers can be quite a headache.

If you're experiencing issues, the problem likely lies here:

$timeout(function () {
        $('#article').highlight(_highlights, { element: 'em', className: }, 200);

Using #article.html() here may result in unexpected output due to Angular's synchronization system conflicting with the way Jquery interacts with the DOM. Adding asynchronous JavaScript into the mix only complicates things further when working on multiple tasks simultaneously.

A better approach would be to set the HTML to an Angular scope variable before applying any Jquery operations, like so:

$timeout(function () {
        $('#article').html($scope._article);
        $('#article').highlight(_highlights, { element: 'em', className: }, 200);

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

Optimize Date Formatting within a React Application Using Material UI Data Grid

I am currently working with MUI Data Grid Pro and I have an issue with filtering dates in the format dd-mm-yyyy. While the dates are displayed correctly in the columns, the filtering defaults back to mm-dd-yyyy. https://i.stack.imgur.com/Ue12K.png For mo ...

Error encountered during JSON parsing: unexpected non-whitespace character found after the JSON data on line 1

I have implemented a simple JavaScript code (using AngularJS, but that's not important) like this: app = angular.module('app', []); app.controller("NavCtrl",function($scope,$http){ var serviceBase = 'api/'; $http.get(serv ...

Issues encountered with the functionality of the AngularJS greetController Controller

Currently exploring AngularJS, I am following a tutorial and have hit a roadblock trying to get the greetController controller to function properly. Below is the HTML code: <!DOCTYPE html> <html> <head> <title>HTML.it</titl ...

"Implementing a Two-State Toggle Button Using the slideToggle Method in JQuery

I'm struggling to implement two different states for the toggle button. Currently, clicking the button reveals the hidden h1 text, but it fails to hide the text when the slideToggle() method is used to retract it. Just to clarify: I want the calendar ...

The Mongodb database is failing to recognize updates made to the Mongoose schema

I have already created my database with the following schema: const ProjectSchema = new mongoose.Schema({ name: { type: String }, description: { type: String }, client: { type: mongoose.Schema.Types.ObjectId, ref: 'client& ...

retrieve data from an asynchronous request

Utilizing the AWS Service IotData within an AWS Lambda function requires the use of the AWS SDK. When constructing the IotData service, it is necessary to provide an IoT endpoint configuration parameter. To achieve this, another service is utilized to obta ...

The function textfield.value = "" is functional in Safari and Chrome, but experiences issues in Firefox

I'm facing an issue with a function that removes text from a textfield named termsField using JQuery to clear the content of a div called definitionContainer. This function is triggered when a user clicks on a button. function clearText(target){ ...

Connecting the v-model in a Vue.js child component to update the parent value

I've encountered an issue with a vue component where I'm trying to link a text input in the child template to a variable in the parent using v-model, but it doesn't seem to be working. How can I make this work? Currently, I am using Vue.js ...

Issues with invoking C# event through ajax communication

Whenever I click the Button, an Ajax method is called that triggers a webmethod on the server side. However, currently, the [WebMethod] is not being executed as expected. Below are the snippets of both the Ajax and server-side code: Ajax code $(document ...

Creating a JavaScript pop-up featuring a dynamic table (example using Leaflet.js)

If you explore the leafletjs quickstart guide, specifically in the section labeled "Working with popups", try clicking on the blue marker displayed on the map. A popup will appear with the simple text "hello". But wouldn't it be interesting to have th ...

Combine multiple values into a single input in the number field

I have a number type input field... What I am looking for is: Age-Height-Weight 20-180-80 Is there a way to ensure that users input data in this exact format and then have the final result inserted into the input field with type="number" and submitted? ...

Express does not transfer objects to the view layer

I'm attempting to transfer a user object from passport to the browser, but when I check the console all I see is window.user undefined. Within the route, I've confirmed the object's existence with console.log("USER:"+JSON.stringify(req.user ...

An error message of "TypeError: Contact is not a constructor" is displayed in Postman when attempting to validate JSON data for a post

After successfully running node app.js without any errors, I encountered an issue when trying to route localhost:3000/api/contact and post JSON data using Postman. Despite looking at similar questions, I am still unable to resolve the problem. Below is a s ...

Use the jQuery library to detect scrolling and toggle the CSS class between 'selected' and

I am trying to dynamically add the "selected" class to a[href] when a specific DIV comes into view while scrolling. However, I want to remove this class completely once the DIV has been scrolled past. const links = $(".cd-faq-categories li a"); // Find al ...

AngularJS triggers the function on all controllers

I encountered a problem with a specific function in my code. The issue is that the scrollFunction continues to get triggered even when I navigate to another page. I would like to limit this functionality to only apply to a particular page within the cont ...

The error message received was: "npm encountered an error with code ENOENT while trying to

About a week ago, I globally installed a local package using the command npm i -g path. Everything was working fine until today when I tried to use npm i -g path again and encountered the following error: npm ERR! code ENOENT npm ERR! syscall rename npm ER ...

What allows this Jquery behavior to function within a single-threaded setting?

Initially, the task at hand is to conduct a series of validations on a server for every keystroke made. This process is carried out through AJAX. An issue arises when the penultimate (invalid) response is received from the server after the ultimate (valid) ...

What is the best way to access an item within an item using HTML and AngularJS?

I attempted to retrieve a value from two dynamic objects using AngularJS. <div ng-controller="SampleController"> <div> {{item['111']['price']}} </div> within the SampleController $scope.item={111:{price:"232"},112:{ ...

Enhancing Drupal Websites with Dynamic Page Updates using AJAX

I have a select list on my form that displays various options. When the user chooses an option from the list, I want to pass that value into a PHP function to retrieve a list of IDs associated with it. Subsequently, I aim to update the URL with both the se ...

After converting TypeScript to JavaScript, the import functionality appears to be malfunctioning

homepage.ts export function homepage () {...rest of function} app.ts import { homepage } from "./homepage"; homepage(); index.html <script src="/dist/app.js" type="text/javascript"></script> Error: Uncaught Sy ...