Why is $watch not working inside tabs in AngularJS?

Check out this example on Plunker

Hello everyone,

In the provided example, there are two input text boxes created - one outside the tab and another inside. A watch function has been implemented for both of them. However, the watch function for the input box inside the tab is not functioning as expected, while the one outside works fine. The coding seems to be identical in both cases, so it's unclear why one is working and the other isn't.

Any assistance on resolving this issue would be greatly appreciated.

Answer №1

It is recommended to use a dot in your ng-model. More information can be found here

To ensure that your code functions correctly, make sure it follows this format:

In the JavaScript file:

.controller('sample', function($scope){
    $scope.user = {};
    $scope.cancel = function(){
      console.log("cancel")
    }
    $scope.$watch('user.FirstName', function() {
        console.log("FirstName")
    //  fetch();
    });
    $scope.$watch('FirstName1', function() {
        console.log("FirstName1")
    //  fetch();
    });
      //Here I need to Change Selected Tab
  })

In the HTML file:

<pane id="FirstTab" title="First Tab">
    <div><div class="form-group">
        <label for="text">First Name</label>
        <input type="text" required ng-model="user.FirstName" class="form-control" id="FirstName">
    </div>
        <div class="form-group">
            <label for="text">Middle Name</label>
            <input type="text" required ng-model="user.MiddleName" class="form-control" id="MiddleName">
        </div>
        <div class="form-group">
            <label for="text">Last Name</label>
            <input type="text" required ng-model="user.LastName" class="form-control" id="LastName">
        </div>

    </div>
</pane>

Answer №2

Try a different approach by utilizing ng-change as well. This feature monitors any changes in the model and triggers the function accordingly. Implement this instead of using $watch.

 $scope.change = function() {
  console.log("FirstName")
}

Incorporate ng-change in the template like this:

<input type="text" required ng-model="FirstName" ng-change="change()" class="form-control" id="FirstName">

For access to the modified plunk, click here

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

Is it possible for web browsers to set a timeout on an XmlHttpRequest while it is still active?

When dealing with asynchronous XMLHttpRequests that take a long time to retrieve data from the server, I am searching for a way to abort them. Setting a timeout before sending the XHR is not feasible due to the length of these requests. Although calling X ...

Angular application cannot be launched in the Windows operating system

We have implemented an Angular application on a Windows 8.1 machine. We have successfully installed the necessary dependencies such as bower, npm, and node server. Upon starting the application with npm start, we encounter an issue after logging in. Inste ...

What is the best way to continuously execute the ajax request for downloading a pdf file?

if( $.isArray(certTypeReq) ){ $.each(certTypeReq,function(key,certType){ $.ajax({ url: baseUrl+"/user/certificate/getlink", type: 'GET', data: { 'certType' : certType}, ...

Calculate the sum of floating point or decimal numbers from a textarea using JavaScript

I'm trying to work with a text area that contains decimal/float numbers. However, the code I found online seems to be ignoring commas and periods when summing up the values. Is there a way to handle decimal/float numbers correctly in this scenario? ...

What is the process for broadcasting an object with socket.io?

I am encountering an issue with sending responses in my code. socket.on('findUserMessages', (userName) => { io.sockets.connected[socket.id].emit('Checking-message', { type: 'ss', text: bot, use ...

What is the best way to compare the lengths of all nested child elements with each other?

I have an object with nested children, like this: $scope.artists.materials.items[] //contains list of items Now I need to compare the total length of each artist's list of items. If there is a mismatch in the number of items between artists, I want ...

What could be the reason for npm start not running?

For some reason, I am encountering the following error: C:\AppData>npm start npm ERR! missing script: start npm ERR! A complete log of this run can be found in: npm ERR! C:\AppData\Roaming\npm-cache\_logs\2019-02-28T1 ...

Creating a real-time search feature with dual streams of terms in Angular 2

After diving into the Angular 2 documentation, I was able to grasp how to implement a live search feature using just one term as a parameter. private searchTermStream = new Subject<string>(); search(term: string) { this.searchTermStream.next(term); ...

My journey doesn't begin at zero

This piece of code triggers an alert message saying 'test 1', followed by an alert indicating the number 8! uri = 'http://www.scriptcopy.com/'; compareuris = new Array(); compareuris[0] = 'http://www.scriptcopy.com/'; compare ...

The most effective method for monitoring updates to an array of objects in React

Imagine a scenario where an array of objects is stored in state like the example below: interface CheckItem { label: string; checked: boolean; disabled: boolean; } const [checkboxes, setCheckboxes] = useState<CheckItem[] | undefined>(undefined ...

Embracing ES6 Imports Over Requires in Node.js

var MCrypt = import('mcrypt').MCrypt; What is the experience of utilizing import instead of require for the above code? It seems challenging to achieve in a single line. ...

Unsure about the approach to handle this PHP/JSON object in Javascript/jQuery

From my understanding, I have generated a JSON object using PHP's json_encode function and displayed it using echo. As a result, I can directly access this object in JavaScript as an object. Here is an example: .done(function(response) { var ...

Is it possible for my code in ReactJS to utilize refs due to the presence of backing instances?

When working with ReactJS components, I often piece together JSX elements to create my code. For example, take a look at the snippet below. I recently came across this page https://facebook.github.io/react/docs/more-about-refs.html which mentions that "Re ...

Embedding an external form using POST method within an iframe

My goal is to have a page containing a POST form load inside an iframe so that users can confirm actions like deleting a listing. I've managed to load the JS and form page within the iframe, but when I interact with the form, it just refreshes the pag ...

Enabling table row scrolling with keyboard navigation in React

Struggling to figure out how to make my table scroll while navigating through the rows using the onKeyDown event. It seems that the event isn't updating when using the keyboard, even though the highlighting of the selected row with selected is working ...

Refresh the redux state within the reactjs component and make use of it in the application

I am in need of assistance with opening a search aid, selecting a value, and retrieving it. After clicking on a button, I activate a search help where I choose data to store. However, I am unsure how to utilize this stored data upon returning. I aim to di ...

What is the best way to access all of the "a" elements contained within this specific div?

Chrome websites are built using the following structure: <div class="divClass"> <a class="aClass"></a> <a class="aClass"></a> <a class="aClass"></a> </div> Utili ...

What is the best way to filter out and combine one array from two arrays in lodash based on their unique properties?

Lodash v 4.17.15 Consider the scenario where two arrays are involved: var users = [{ id: 12, name: Adam },{ id: 14, name: Bob },{ id: 16, name: Charlie },{ id: 18, name: David } ] var jobs = [ ...

How to Stop Browser Tooltip from Displaying HTML Tags within "innerHtml" in Angular 6

In my Angular application, a template is using the following code snippet: ... <span [innerHtml]="textVar"></span> ... The textVar variable is created to allow for special styling on certain characters or strings. It's formatted using th ...

Unable to access the 'propHooks' property of an undefined object while using jQuery's animate function

An issue arises with the following error message: Uncaught TypeError: Cannot read property 'propHooks' of undefined This problem occurs specifically when implementing color animation functionality in jQuery. ...