What could be the reason for scope.$watch failing to function properly?

My AngularJS directive has a template with two tags - an input and an empty list. I am trying to watch the input value of the first input tag. However, the $watch() method only gets called once during initialization of the directive and any subsequent changes to the input value do not trigger it. What could be causing this issue?

You can find my plunk here.

Below is the code snippet:

.directive('drpdwn', function(){
   var ref = new Firebase("https://sagavera.firebaseio.com/countries");

function link(scope, element, attrs){

  function watched(){
    element[0].firstChild.value = 'bumba'; //this gets called once
    return element[0].firstChild.value;
  }

  scope.$watch(watched, function(val){
    console.log("watched", val)
  }, true);

}
return {
  scope:{
    searchString: '='
  },
  link: link,
  templateUrl:'drpdwn.html'
}
})

Edit:

If I include the $interval() function within the link function, everything works as expected. Is this intentional behavior?

Answer №1

There is a lack of digest triggered on the scope, resulting in the function not being called.

A better alternative is to utilize ng-model like this:

http://plnkr.co/edit/qMP5NDEMYjXfYsoJtneL?p=preview

function link(scope, element, attrs){
  scope.searchString = 'bumba';
  scope.$watch('searchString', function(val){
    console.log("watched", val)
    val = val.toLowerCase();
    val = val.replace(/ */g,'');
    var regex = /^[a-z]*$/g;
    if (regex.test(val)) {
      scope.searchString = val;
      // TODO something....
    }
  }, true);

Template:

<input class="form-control"  ng-model="searchString" id="focusedInput"  type="text" placeholder="something" />
<div></div>

Answer №2

In the watcher function, you are assigning the desired value.

function watched(){
    element[0].firstChild.value = 'bumba'; //this is executed once
    return element[0].firstChild.value;
}

This results in the same output as

function watched() {
    return 'bumba';
}

Therefore, the watcher will consistently return the same value.

If you want to set the initial value, do it outside of the watcher:

element[0].firstChild.value = 'bumba'; //this is executed once
function watched(){
    return element[0].firstChild.value;
}

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

Replace particular letters within the text with designated spans

Suppose I have this specific HTML code snippet: <div class="answers"> He<b>y</b> <span class='doesntmatter'>eve</span>ryone </div> Additionally, imagine I possess the subsequent array: ['correct' ...

What is the correct way to execute a jQuery trigger on a checkbox or radio button to simulate a user clicking on it?

My current page utilizes can.js, making it challenging to replicate the issue on jsfiddle.net. The result I am experiencing is as follows: When I click on a checkbox (or even a radio button), an input text box should update accordingly (for example, displ ...

After placing two divs within another div and applying justify content, an unexpected blank space has appeared

I am currently working on a website project using the Next.js framework for React and Tailwind CSS for styling. However, I have come across an issue that is causing some trouble. My goal is to position an image on the right side of the page while keeping t ...

Why is it not performing as expected when removing all non-numeric elements from the array?

let arr = [1, "5", 3, 27, undefined, { name: 'Steven' }, 11]; for (let i = 0; i < arr.length; i++) { if (typeof arr[i] !== 'number') { arr.splice(i, 1); } } console.log(arr); // result: [1, 3, 27, {…}, 11 ...

Require assistance to resolve variable scope problems

Having trouble accessing the names array within the driver.executeScript method. Any suggestions on how to resolve this issue? var webdriver = require('selenium-webdriver'), By = webdriver.By, until = webdriver.until; var driver = new webdri ...

Utilizing jQuery to Extract Values from a List of Options Separated by Commas

While usually simple, on Mondays it becomes incredibly challenging. ^^ I have some HTML code that is fixed and cannot be changed, like so: <a class="boxed" href="#foo" rel="type: 'box', image: '/media/images/theimage.jpg', param3: ...

The date field is being assigned the identical value as the first row in the AngularJs table

Other values are also getting input from the date. Below is the HTML code snippet: name='form_{{columns.dataId}}' ng-init="dateValue = columns.formValue != null ? columns.formValue : ''" ...

Having trouble loading background color or image in three.js

I've been struggling to load a background image or color on my webpage. Despite trying various methods, including commenting out javascript files and checking the stylesheet link, nothing seems to work. Even when I load the three.js scene with javascr ...

Replace automatically generated CSS with custom styles

When using a Jquery wysiwyg editor, I have encountered an issue where it automatically adds code to the textarea at runtime. The problem arises from it inserting an inline style of style="width:320px" when I need it to be 100% width due to styles already ...

What is the best way to capture a 403 response when making a GraphQL API call?

My server handles component rendering and generates an HTML response upon request. During the rendering process, the server initiates a GraphQL call for a specific component which sometimes results in a 403 error. Here is the code snippet: const client = ...

Remove an item from the DOM instantly with React

Having trouble synchronously removing a child from the container? Here is a simplified code snippet demonstrating the current solution using the useState hook. type ChildProps = { index: number; id: string; remove: (index: number) => void; }; fun ...

Find the value of the nearest input field using jQuery

I'm working with HTML code that looks like this: <tr> <td class='qty'><input class='narrow' value='1' /><i class='fa fa-trash' aria-hidden='true'></i></td> < ...

Is my jQuery code generating a large number of DOM objects?

I am currently developing a hex dumper in JavaScript to analyze the byte data of files provided by users. To properly display a preview of the file's data, I am utilizing methods to escape HTML characters as outlined in the highest-rated answer on thi ...

Having trouble with installing Angular JS on my computer

On my machine, I have successfully installed node.js version v0.12.0. However, when attempting to run sudo npm install, I encountered the following errors: npm ERR! install Couldn't read dependencies npm ERR! Darwin 14.0.0 npm ERR! argv "node" "/usr/ ...

Tips for implementing custom fonts in NextJS without relying on external services

Utilizing Fonts in NextJS I have been researching various methods for using self-hosted fonts with NextJS. When attempting the following code, I encountered a [ wait ] compiling ...: @font-face { font-family: 'montserrat'; src: url(&a ...

Converting a table into div elements and subsequently reverting it back to its original table format

[STOP DOWNVOTING: NEW AND IMPROVED] Discovering a simple technique on stackoverflow to transform tables into divs has been quite enlightening. By assigning classes to each tag, such as: <table class="table"> the process of converting from table to ...

When iPhone images are uploaded, they may appear sideways due to the embedded exif data

When trying to upload images from a mobile device like an iPhone, it's common for the images to appear sideways unless viewed directly in Chrome. It seems that this issue is related to the image exif orientation data, which Chrome can ignore but othe ...

Conditionally display content based on the existence of a specific value within an array

Is there a way in AngularJS to display a value using ng-show, such as ng-show = "role in ['admin', 'user', 'buyer']" I want to display a div if the role matches any of the elements in the array. ...

The express-fileupload throws an error saying "ENOENT: unable to locate the file or directory at 'public/images/name.ext'"

I am encountering an error ENOENT: no such file or directory, open 'public/images/name.ext from express-fileupload. I have searched for solutions to this issue, but none of the ones I found seem to work for me. Here are two examples: No such file or d ...

Trouble arises with MySQL query in PHP/jQuery setup

I am currently in the process of developing a user panel where users can change their first and last names. Everything seems to be working fine with the $ajax form handling, as I can use console.log(data) and see {fname: "Damian", lname: "Doman", id: "20" ...