Unable to capture user input text using $watch in AngularJS when applied on ng-if condition

I have developed a cross-platform application using AngularJS, Monaca, and OnsenUI.

In my login view, I check if the user has previously logged in by querying a SQLite database. Depending on whether there is data in the database, I either display a welcome message to the user or show the login text field.

I have successfully implemented a method to query the SQLite database. When a record is found in the database, I set a boolean value to show the welcome message; otherwise, it displays the login text field.

Within my view, I include the following code;

<!-- User not in DB  -->
<div ng-if="showLoginUI">                    
    <div class="input">
        <input type="password" placeholder="User ID" ng-model="userID"/>
    </div>
</div>

I monitor changes in the text field to capture user input, but no actions are recorded as shown above. This is the approach I use to track user interactions with the text field.

$scope.$watch("userID", function (newVal, oldVal)
{
    if (newVal !== oldVal) {
        $scope.newUserID = newVal; // Not getting here
    }
});

However, when I remove the ng-if statement from the example above, the user events are captured. How can I retain the ng-if while still tracking events on the text field?

I attempted to incorporate a $timeout in my $watch function, but this did not resolve the issue.

Answer №1

One of the reasons for this issue is that the ngIf directive generates a child $scope. The main problem arises when using ng-model without adhering to the Dot Rule or controller-as-syntax.

This dilemma was aptly elucidated by Pankaj Parkar in their response to a related query.

To resolve this, you need to instantiate a new object, such as:

$scope.model = {};

Subsequently, structure your ng-model as follows:

ng-model="model.userID"

Refer to this functional demonstration:

angular.module('app', [])
  .controller('mainCtrl', function($scope) {
    $scope.model = {};
    
    $scope.$watch("model.userID", function(newVal, oldVal) {
      if (newVal !== oldVal) {
        $scope.model.newUserID = newVal;
      }
    });
  });
<html ng-app="app">

<head>
  <script src="https://cdnjs.cloudflare.com/ajax/libs/angular.js/1.5.7/angular.min.js"></script>
</head>

<body ng-controller="mainCtrl">
  <button type="button" ng-click="showLoginUI = !showLoginUI">Hide/Show</button>
  <div ng-if="showLoginUI">
    <div class="input">
      <input type="password" placeholder="User ID" ng-model="model.userID" />
    </div>
  </div>
  <div ng-if="model.newUserID">
    <hr>
    <span ng-bind="'Working: ' + model.newUserID"></span>
  </div>
</body>

</html>

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

Cordova launching a webpage in mobile browser

Hey, I'm encountering a problem. I have customized my CordovaWebView.java class so that when I press the device back button, the application prompts me to close it. public boolean backHistory() { // Check webview first to see if there is a h ...

Mastering the art of iterating through arrays using node.js request()

After transitioning from passing single values to multiple values in my node API, I encountered an issue where the API no longer responded. Here is an example of single values for fields: tracking: "123", // Only one tracking number carrier: "usps" // On ...

Any ideas on how to potentially establish a default route based on conditions with react-router-dom v6?

Managing two pages, Page1 and Page2, requires conditional configuration for setting one as the homepage based on a specific condition. Additionally, all URLs must be prefixed with an ID. Take a look at the code snippet below: <Routes> <Route pat ...

Running JavaScript code within views

While dealing with AngularJS, I have an index page that includes a <div ui-view></div>. When a specific URL like #/offers/new is entered, it loads a page such as new-offer.html into the ui-view. In my javascript code block within the index.htm ...

When working with JavaScript and Node.js, it is not possible to access an object's index that is

Utilizing babyparse (PapaParse) in nodejs to convert CSV to JavaScript objects has been quite challenging for me. After processing, the output of one object looks like this: { 'ProductName': 'Nike t-shirt', ProductPrice: '14.9 ...

Ways to assign values to an array within an object

I'm attempting to transfer the contents of one array into an array within an object, but I keep encountering this error: Type 'any[]' is not assignable to type '[]'. Target allows only 0 element(s) but source may have more. Here ...

Is it possible to assign a deconstructed array to a variable and then further deconstruct it?

Is there a way to deconstruct an array, assign it to a variable, and then pass the value to another deconstructed variable all in one line of code? Take a look at what I want to achieve below: const { prop } = [a] = chips.filter(x => x.id == 1); Typic ...

What is the method for adjusting the size of text while rendering on a canvas?

When it comes to scaling text with CSS transform scale, for instance: transform: scale(2, 4); fontSize: 20px // Is including fontSize necessary? I also have the task of displaying the same text on a canvas element. function draw() { const ctx = document ...

Basic inquiry about Ajax

Would you like to know a simple solution for refreshing a specific area of your website using ajax? Instead of having JavaScript constantly checking for changes on the server, is there a way for the server to send data when a certain event occurs? Imagine ...

What methods do Google and Yahoo use to update the URL displayed in the browser's status bar?

Have you ever noticed that on Google and Yahoo search pages, the URLs of the search result links actually point to google.com or yahoo.com? It's a clever trick they use by adding extra arguments to the URLs that allow for redirection to the actual sea ...

`Can you provide instructions on modifying CSS using JavaScript once the window size reaches a specified threshold?`

Is there a way to use JavaScript to automatically adjust the font size when the screen reaches 1050px? ...

The color scheme detection feature for matching media is malfunctioning on Safari

As I strive to incorporate a Dark Mode feature based on the user's system preferences, I utilize the @media query prefers-color-scheme: dark. While this approach is effective, I also find it necessary to conduct additional checks using JavaScript. de ...

Arrange components within the form

Just started experimenting with this a few days ago. In my form, there is a text field and a button that I want to align side by side at the center of the form. .row { width: 100%; margin-bottom: 20px; display: flex; flex-wrap: wrap; } .col-6 { ...

Error: Unable to access the 'name' property of an undefined variable

When running the code, I encountered a "TypeError: Cannot read property 'name' of undefined" error, even though when I console.log it, it provides me with the object import React from "react"; class Random extends React.Component { constructo ...

Error encountered in jQuery validation: Uncaught TypeError - $(...) ""valid is not a function" is displayed with proper references and order

When I try to call a function, I keep getting an error message that says "Uncaught TypeError: $(...).valid is not a function"... JS $('input[data-val=true]').on('blur', function() { $(this).valid(); }); HTML <div class="col-x ...

Retrieve documents from MongoDB database that have specific characteristics

Hello everyone, Today I'm trying to navigate mongoose queries. Imagine we have a collection like this: [ {letter: "A", name: "Books", action: "read"}, {letter: "B", name: "Notebook", action: &q ...

($rootScope: busy) Applying changes right now

Whenever I try to make changes to the UI grid after refreshing the data, I keep encountering this error message: angular.js:13236 Error: [$rootScope:inprog] $apply already in progress http://errors.angularjs.org/1.5.0/$rootScope/inprog?p0=%24apply ...

The combination of Array.pop and Array.indexOf is not functioning as expected

I'm having an issue with using Array.pop(Array.indexOf(value)). It seems to always delete the last element in the index, even if the value of that index is not what I intended. Can someone provide some guidance on how to resolve this? CheckBoxHandle ...

Adjust the size of an element by utilizing a different element

I'm facing a challenge with this code. I need to dynamically set the width of the "wrap-description" divs to be equal to the width of the corresponding "picture-damage" images plus an additional 20 pixels. Since there will be multiple elements for bot ...

Incorporating multiple markers into Google Maps with the help of a JSON file

I am struggling to display markers on a map for 20 restaurants from a JSON file. It seems like I may not be retrieving the data correctly. Any help or guidance in the right direction would be greatly appreciated. My current code is as follows: var map; ...