Directive in AngularJS is a reusable component that allows

Let me explain my situation. I am dynamically adding a block of code using JavaScript and binding it to my AngularJS scope. Everything seems to be working fine, except for one issue. There is a directive on a text box that works properly. However, the $watch function triggers when any other text box is changed for the first time, but not subsequently. Below is the code snippet:

$('.addNew').click(function(){
    var uniqid = Date.now();
    var html= '';
    html += '<section class="newItem" id="'+uniqid+'">';
    // Rest of the HTML code...
});

Here is the directive used in the code:

app.directive('costCheck',function($compile,$rootScope){
$rootScope.gName= "What did i buy?";
    return{
        restrict: 'A',
        link: function(scope,element,attrs){

                scope.$watch('cost',function(oldval,newval){alert(attrs.name);
                    if(attrs.name === 'cost'){
                        alert(oldval+'--'+newval);
                    }
                });

        }

    }
});

The problem lies in why the $watch function triggers for other text boxes as well. Any suggestions?

Answer №1

Keep in mind that Angular relies on dirty checking to update the View by triggering all watches to check for any changes.

To ensure only relevant changes are detected, consider adding an if condition to compare newVal and oldVal:

scope.$watch('cost',function(newVal, oldVal){
  if (newVal !== oldVal){
    alert(oldval+'--'+newval);
  }
});

Alternatively, you can use attrs.$observe to monitor attribute changes like this:

In the DOM, switch from using cost-check directive to cost-check="{{cost}}", then replace $watch with $observe:

attrs.$observe('costCheck', function(val) {
  console.log(scope.$eval(val));
});

See it in action: http://jsfiddle.net/HB7LU/3018/

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

Dealing with asynchronous tasks in JavaScript

I am currently delving into the world of Node development and struggling to grasp the asynchronous nature of JavaScript and Node.js. My project involves creating a microservices backend web server using Express in the gateway service, which then translates ...

Recalling the position of the uploaded image within a v-for loop

I am struggling to solve this issue. Currently, I am utilizing Vue.js in an attempt to construct a dashboard where users can upload up to five images of visitors who are authorized to access a specific service provided by the user. Below is the code snip ...

Challenges with inferring return values in Typescript generics

I'm encountering an issue with TypeScript that I'm not sure if it's a bug or an unsupported feature. Here is a Minimal Viable Example (MVE) of the problem: interface ColumnOptions<R> { valueFormatter(params: R): string; valueGette ...

Tips for choosing elements based on the length of an array

When using an each function, I scan the DOM to find multiple elements with a specific className. Depending on the length of this ClassName, it will create an array that is either 2 or 4 elements long. I need to distinguish between these two types of elem ...

Error message from Angular development server: Channel is reporting an error in handling the response. The UNK/SW_UNREACHABLE options

After recently installing a new Angular app, I encountered an issue while running 'ng serve'. The application initially loads without any problems, but after a few seconds, I started seeing a strange error in the console. Channel: Error in handle ...

Is it impossible to modify an enumerable attribute within a JSON.stringify replacer function?

I'm having some trouble trying to serialize non-enumerable properties within the replacer function. Can someone point out what might be going wrong in this code snippet? Any help would be greatly appreciated. var obj = {x:1,y:2}; Object.definePrope ...

Error with object props in React using Typescript

Here's a scenario; I have a list of 'Reviews' that I am trying to render. The Proptype for these reviews is as follows: export interface Props { title: string; name: string; reviewdesc: string; rating: number; } In the pare ...

"Utilizing jQuery to integrate an Ajax-powered Gauge using Google Visualization API

I need help creating a dynamic dashboard gauge that updates using ajax. The code snippet below shows what I have so far, but I'm struggling with updating the gauge itself. Any advice or suggestions on how to achieve this? google.load('v ...

What is the method for retrieving a child element using its ID in JavaScript?

Below is the HTML code I am working with: <div id="note"> <textarea id="textid" class="textclass">Text</textarea> </div> I am trying to retrieve the textarea element without using document.getElementById("textid"). This is what I ...

What are the steps to set up auto-building with create-react-app?

I've been utilizing create-react-app for some time now. Autoreloading with 'npm start' or 'yarn start' has been working well on its own, but now I'm facing another issue. Currently, I am running the app on an Express server th ...

The scope of the UI Bootstrap directive does not seem to be getting refreshed

Currently working on a project that involves AngularJs, I am seeking assistance in creating a dialog box where users can input a string. The goal is to display this string later on the page prominently. To achieve this, I opted for the modal directive fr ...

Struggling to transfer information between POST and GET requests in Node/Express

Just diving into node/express, currently developing a weather application that receives location data from a form submission <form method="POST" action="/"> <input id="input" type="text" name="city" placeholder="Search by city or zip code" /> ...

Ensure to verify the `childProperty` of `property` within the `req.checkBody

When working with Node.js, a common practice is to use code like the following: req.checkBody('name', 'Group name is required.').notEmpty(); In a similar fashion, I have implemented something along these lines: req.checkBody('pa ...

What is a unique method for creating a wireframe that replicates the structure of a square grid without using interconnected nodes

Currently, I am in the process of designing the wire frame styles for human body OBJs and my goal is to achieve a wire frame similar to the image below. In the following lines, you will find the code snippets that illustrate how I create the wire frame alo ...

How can I replicate the functionality of the span element using Javascript?

Using Javascript, I am able to display a paragraph without the need for HTML. By adding it to an HTML id, I can manipulate individual words within the text. My goal is to make specific words cursive while keeping the entire paragraph in its original font s ...

React - error caused by an invalid hook call. Uncaught Error: React encountered a minified error with code #

My goal is to incorporate the micro-frontend concept by implementing various react apps. Container Header Dashboard All three are separate applications. I intend to utilize the Header and Dashboard apps within the Container app. For the Header app, it& ...

unable to reach the factory through the controller

In my AngularJS application, I've developed a factory called 'paging' that provides numbers for pagination. expenseApp.factory('paging', function() { this.pages = function(min, max, step) { if (max <= 5) { min = 1; ...

Interact with USB drive using electron to both read and write data

I am currently developing an electron project that involves copying files from a computer to USB drives. I need the ability to transfer files and folders to the destination USB drive, as well as determine the amount of free space on the drive. I have expe ...

Is it possible to utilize setIn for establishing a fresh index on an array that is currently empty?

Having trouble using Immutable in this specific structure: myMap = Map({a: [], b: []}); myMap.setIn(['a', 0], 'v'); An exception is being thrown when trying to do this immutable.js Error: invalid keyPath at invariant (immutable. ...

What is the solution to adding values from a counter?

I am trying to create a JavaScript counter: function animateSun() { var $elie = $("#sun"); $({ degree: 0 }).animate({ degree: 360 }, { duration: 190999, easing: 'linear', step: function(val) { now = Math.round ...