What is the best method to remove duplicate watches in AngularJS?

After creating a basic TODO app using AngularJS, I discovered some interesting features.

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

The app allows me to manage my list of tasks, such as deleting, marking as completed, and adding new ones.

A unique functionality is the ability to edit the task title by double-clicking on the bold text, triggering a text input field to appear:

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

In each row under the ng-repeat directive, there's an invisible input element that switches its visibility based on certain conditions:

<li ng-repeat="todo in vm.todos....."  ...>

    <div ng-hide="vm.isTheEdited(todo)"> //this is "read" mode
         ....show checkbox + Label + Delete button
    </div>

    <input  ... show="vm.isTheEdited(todo)"....  /> // this is the "edit" mode

  </li>

Everything seems fine with these functionalities.

However, I came across a code snippet that counts watchers in an AngularJS app. Intrigued, I decided to enhance it to display unique items in a string format.

(I simply added):

Array.prototype.unique = function(a){
    return function(){ return this.filter(a) }
}(function(a,b,c){ return c.indexOf(a,b+1) < 0 })

console.log(getWatchers().unique().length);
console.log(getWatchers().unique().map(function (a){return a.exp;}));
)*

Focusing on duplicates,

I noticed numerous duplicated watchers in the app. This led me to question why the duplicates exist and how I can reduce their number while eliminating them entirely.

Take a look at the results below:

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

Question: What causes the high number of duplicate entries in the watchers, and what steps can be taken to decrease and prevent duplication?

The situation arose from utilizing ng-show and hide based on specific function values within the app.

Answer №1

There doesn't appear to be any duplicates here: both the ngShow and ngHide directives create watchers, and it seems impossible to avoid having at least two watchers for each row in this scenario.

The only way to eliminate all watchers is by implementing a custom directive that:

  • hides the label and displays the input on double click
  • shows the label and hides the input upon pressing enter

For example:

module.directive('customClick', function() {
  return {
    link: function(scope, element) {
      var span = element.find('span'),
          input = element.find('input');

      input.hide();

      span.on('dblclick', function() {
        if (span.is(':visible')) {
          span.hide();
          input.show();
          input.val(span.text());
        }
      });

      input.on('keypress', function(e) {
        if (e.which === 13) {
          input.hide();
          span.show();
          span.text(input.val());
        }
      });
    }
  }
});

HTML:

...
<div ng-repeat="todo in vm.todos" custom-click>
  <span>{{todo}}</span><input>
</div>
...

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

Difficulty recognizing sessions in production for a self-hosted Next.js application using Clerk Dev Auth

Having trouble finding the next step in debugging as I couldn't resolve the issue on Clerk's Discord or GH Issues. It seems like it might be a Next.js problem rather than a Clerk one? I am currently running a self-hosted next.js app in a docker ...

JavaScript: A timer that relies solely on the concept of TIME

Hello all, I have a specific question regarding starting a timer in JavaScript for a test scenario. Despite researching on my own and seeking help on various platforms, I haven't found a solution that fits my requirements. I am looking to implement a ...

Ways to customize easypiechart appearance with CSS styling

I am looking to create a circular counter similar to the one shown below. I have tried using easy-pie-chart but I am unsure how to style the circles to look like the example provided. Is there a way to achieve this through CSS? Any recommended resources o ...

Shifting attention from one input to another by utilizing a barcode scanner

Utilizing a barcode scanner, I am inputting data into the fields of a webpage. The form is set up with autofocus on the initial input field. However, upon entering the first barcode in the opening field, the focus should shift to the following input field. ...

Having trouble retrieving the full HTML code with the execute_script function in Python while web scraping

Currently, I am in need of HTML code to perform web scraping using Python. The particular website I am working with is that of a real estate agency. Prior to executing the onclick event for a button that changes pages, it is crucial for me to first obtain ...

Video player for Angular 2

Hey there! I am currently exploring Angular 2 and attempting to create a video playlist feature. My goal is to showcase my favorite videos in a table layout, where clicking on a row will lead to the playback of the selected video. Right now, I am passing t ...

Utilize Puppeteer for Web Scraping to Extract Products with an Array of Images

I am currently developing my portfolio by working on a variety of small projects, with my current focus on web scraping. Using Puppeteer, I have successfully scraped basic test websites. However, my goal now is to tackle more advanced challenges, such as ...

How can we convert a mixed-case word into one or more words with initial capital letters?

Is there a way to convert caps and spaces to their normal form? For instance, can the word coreControllerC4a be transformed into Core Controller C4a automatically when a function is triggered? ...

Capture the Promise Rejection

During my test with WebdriverIO, I consistently encounter an issue specifically with this line of code: await browser.waitForVisible('#tx-sent li', 15000) Intermittently, a Promise rejection error occurs: Error: Promise was rejected with the ...

The alpha value returned by gl.readPixels in Three.js will consistently be 255

Is there a way to retrieve pixel values from a threejs application? const gl = renderer.context; const currentFrame = new Uint8Array(gl.drawingBufferWidth * gl.drawingBufferHeight * 4); // read image data from gl gl.readPixels(0, 0, gl.drawingBufferWidth ...

Having trouble deleting element despite having the correct ID?

Whenever I click on the map, it adds an element to the map div using this line of code: $('#map').append('<label>test:</label><input type="hidden" name="map_coords" id="' + e.latlng.lat + '" value="' + e.latlng ...

Angular Unit testing error: Unable to find a matching route for URL segment 'home/advisor'

Currently, I am working on unit testing within my Angular 4.0.0 application. In one of the methods in my component, I am manually routing using the following code: method(){ .... this.navigateTo('/home/advisor'); .... } The navigateTo funct ...

Implementing SVG in NextJS 13 with custom app directory: A step-by-step guide

Recently, I decided to explore the app directory and unfortunately ran into some issues. One of the main problems I encountered was with image imports. While PNG images imported without any problem, SVG images seemed to break when importing in /app. For i ...

Launch both client and server simultaneously with a single command by utilizing Vue-cli and Webpack

Currently, I am setting up a Vue client with Vue-cli 3 that utilizes Webpack. (To start the client, I run "yarn dev --open") In addition, I am developing a server with an API for the client. (To run the server, I execute "node server/server.js") Is th ...

Exploring ways to showcase informational alerts when a link is hovered over by the mouse

I am currently working on a website that showcases links utilized by my team. One specific requirement is that when a user hovers over a link, note information should be displayed. Although the simplest solution would be to not list the link if it's n ...

How to dynamically change the border-top color of an <a> tag in a menu using a jQuery loop

I am interested in adding a colorful border-top to my menu using jQuery. I know this can be achieved with HTML by including style="border-top-color: red;", but I want to explore the jQuery method. Here is what I have attempted so far: var colors = [ ...

Enhancing Javascript with ES6 for nested for loop operations

Hey there, I have a question about converting a nested for loop into an Array map/ES6 way. How does that work when dealing with nested for loops? for (var i = 0; i < enemy.ships.length; i++) { for (var n = 0; n < enemy.ships[i].locat ...

storage location for data in JSON format

When using content type : "application/x-www-form-urlencoded", the result is stored in Request.Form in Asp MVC. However, for "application/json", the storage location cannot be found. Below is the code that is being used: AJAX part // reading form da ...

Internet Explorer 11 refuses to acknowledge Angular JS variable

While this code functions properly in Chrome, it does not display the background color when viewed in Internet Explorer 11: span.fa.fa-icon-only(style='background-color: #{{vehicle.visual_color}};', rr-tt='{{vehicle.color_name}}') It ...

Creating a cascade of falling balls with a single click: Here's how!

I'm currently working on a project where I have a ball dropping from the cursor location and redropping when the cursor moves to another position. However, I want to be able to create a new ball every time I click the mouse. I attempted the following ...