The challenge of Angular form data binding

I'm encountering an issue with binding an input box to a controller in Angular. Despite following tutorials, the model never updates when I access the property or check the scope using AngularJS Batarang.

Upon form submission, $scope.licenceKey remains empty!

<div ng-app="licenceApp" ng-controller="licenceController">
    <form name="licenceForm" ng-submit="applyKey()" novalidate>
        <span ng-if="!Applying">
            <input type="text" ng-model="licenceKey" ng-disabled="Applying" ng-model-options="{ debounce : { 'default' : 150 } }" username-available-validator required />
            ...

JS:

angular.module('licenceApp.controllers', [])
    .controller('licenceController', function ($scope, licenceAPIservice, $filter) {
        $scope.licenceKey = "";
        $scope.Applying = false;
        ...
        $scope.applyKey = function () {
            $scope.Applying = true;

            // $scope.licenceKey is always empty here!!
            licenceAPIservice.applyKey($scope.licenceKey).then(function (data) {
                console.log(data);

                // Update model once we have applied the key
                $scope.update();
            }, function () {
                $scope.Applying = false;
            });
        };

The username directive (although its name needs updating to reflect its function)

angular.module('licenceApp.directives', [])
    .directive('usernameAvailableValidator', function ($http, $q, licenceAPIservice) {
        return {
            require: 'ngModel',
            link: function ($scope, element, attrs, ngModel) {
                ngModel.$asyncValidators.usernameAvailable = function (username) {
                    var deferred = $q.defer();

                    licenceAPIservice.validateKey(username).then(function (data) {
                        if (data.data) {
                            deferred.resolve();
                        }
                        else {
                            deferred.reject();
                        }
                    }, function () {
                        deferred.reject();
                    });

                    return deferred.promise;
                };
            }
        }
    });

Despite entering text into the input, $scope.licenceKey always remains empty. However, the custom validation on the input functions correctly.

It's worth noting that binding to Applying for controlling view states does work!

Update

I found that by using

$scope.licenceForm.licenceKey.$modelValue
, I can retrieve the value. But why is this necessary?

Update 2

If I initially set $scope.licenceKey = "test";, it displays in the textbox on page load. However, any modifications to the textbox do not update this value.

Answer №1

It seems that the issue is arising because of your utilization of ng-if instead of ng-show directive.

The reason behind this discrepancy lies in the fact that ng-if removes the element from the DOM, whereas ng-show employs CSS rules to conceal the element.

You can explore a live example illustrating this distinction by following this link: http://jsfiddle.net/q9rnqju5/.

HTML

<div ng-app="app">
    <div ng-controller="controller">
        <div ng-show="!applying1">
            <input ng-model="value1" />
            <button ng-click="apply1()">Submit</button>
        </div>
        <div ng-if="!applying2">
            <input ng-model="value2" />
            <button ng-click="apply2()">Submit</button>
        </div>
    </div>
</div>

JS

var app = angular.module("app", []);

app.controller("controller", ["$scope", "$timeout", function($scope, $timeout) {
    $scope.apply1 = function() {
        $scope.applying1 = 1;
        $timeout(function() {
            console.log($scope.value1);
            $scope.applying1 = 0;
        }, 1000);
    };
    $scope.apply2 = function() {
        $scope.applying2 = 1;
        $timeout(function() {
            console.log($scope.value2);
            $scope.applying2 = 0;
        }, 1000);
    };
}]);

Upon submission, you will observe that the first input (implemented with ng-show) retains its value, while the second input (operating on ng-if) forfeits its 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

Can you provide the proper syntax for the Jquery done() function?

I'm currently dealing with the code below: However, I encountered an error on line 6: Uncaught SyntaxError: Unexpected token { Even after reviewing the documentation for the done() function, I'm unable to identify my mistake here. ...

Troubleshooting: Why Files are Not Being Served by

I have noticed that there have been similar questions asked about this topic before, but I couldn't find a solution to my problem by reading the responses. I am trying to get my Node.js app to serve my files, and it seems like the page is correctly r ...

405 error: NGINX blocking POST method in Django DRF Vue.js application

I have encountered a strange issue while building my ecommerce site. Everything seems to be working fine, except for the forms. When attempting to post content, I keep receiving a 405 method get not allowed error. It's confusing as I am trying to use ...

Convert JSON objects within an array into HTML format

Is there a way to reformat an array of JSON objects that has the following structure? [{"amount":3,"name":"Coca-Cola"},{"amount":3,"name":"Rib Eye"}] The desired output in plain HTML text would be: 3 - Coca-Cola 3 - Rib Eye What is the best approach to ...

Tips for refining a list to only include items that contain every element from a specified array

Is there a way to search for all elements in an array and display them if they are all present? For instance, consider the following: const data = [ { "languages": ["JavaScript"], "tools": ["React", "Sass"] }, { "languages": ["Python" ...

Using Node.js to read and replicate a JSON file

As someone who is relatively new to the world of NODE.JS, I am eager to level up my skills. Currently, I have a NODE.JS script that gathers data from a feed, resulting in a large JSON file. This file is then used by webpages and mobile apps to display con ...

Cypress: Uncovering the method invoked by a button click

I'm currently utilizing Vue3 with Vite and Cypress. My Vue3 component utilizes the script setup SFC syntax. Below is the code snippet for my component: <template> <div> <button data-cy="testBtn" @click="btnClick()&q ...

Issues with Angular-Trix compatibility with Internet Explorer 10

I am currently using the Angular-trix rich text editor, which is functioning perfectly in all browsers including IE 11. However, I am encountering issues with it not working in IE10 or earlier versions. An error message that keeps appearing states: Una ...

Identifying when a fetch operation has completed in vue.js can be accomplished by utilizing promises

Currently, I am facing a dilemma in my Vue.js application. I am making an API call within the created() hook, but there are certain tasks that I need to trigger only after the API call has been completed. The issue is that this API call usually takes aroun ...

Using a series of nested axios requests to retrieve and return data

Currently, I am utilizing Vue and executing multiple calls using axios. However, I find the structure of my code to be messy and am seeking alternative approaches. While my current implementation functions as intended, I believe there might be a more effic ...

Detecting Collisions in a Canvas-Based Game

As part of my educational project, I am developing a basic shooter game using HTML5 canvas. The objective of the game is to move left and right while shooting with the spacebar key. When the bullets are fired, they travel upwards, and the enemy moves downw ...

My AngularJS integrated with Spring MVC is failing to render the desired page

Hello everyone, I'm fairly new to AngularJS and Spring MVC. I've managed to set up a basic application, but unfortunately, when I try to load it, nothing appears on the screen. The console shows a 404 error. I've double-checked everything, b ...

How can you determine if a user has selected "Leave" from a JavaScript onbeforeunload dialog box?

I am currently working on an AngularJS application. Within this app, I have implemented code that prompts the user to confirm if they truly want to exit the application: window.addEventListener('beforeunload', function (e) { e.preventDefault ...

Bringing back a Mongoose Aggregate Method to be Utilized in Angular

I'm having trouble returning an aggregate function to Angular and encountering errors along the way. I would really appreciate some assistance with identifying the mistake I am making. The specific error message I receive is Cannot read property &apos ...

Guide on loading xml information from a web browser using JavaScript

I have been working on loading data from the browser using a URL and currently utilizing JavaScript to achieve this. window.onload = function() { // This is the specific URL I am attempting to load data from. // The XML fi ...

During the update from Three.js 68 to 69, an error occurred: Unable to access the property 'boundingSphere' of an undefined object

While upgrading my project from Three.js version 68 to version 69, I encountered an error stating Uncaught TypeError: Cannot read property 'boundingSphere' of undefined on line 6077 of Three.js v69: This error pertains to a function within the T ...

Node.js - Hitting maximum call stack size limit despite using process.nextTick()

I am currently developing a module for creating "chainable" validation in Express.js: const validatePost = (req, res, next) => { validator.validate(req.body) .expect('name.first') .present('This parameter is required') ...

What is the best way to incorporate a new attribute into an array of JSON objects in React by leveraging function components and referencing another array?

Still learning the ropes of JavaScript and React. Currently facing a bit of a roadblock with the basic react/JavaScript syntax. Here's what I'm trying to accomplish: import axios from 'axios'; import React, { useState, useEffect, useMe ...

Grabbing the mouse in Firefox

Are there any alternatives to the .setCapture(); and .releaseCapture() functions in Firefox that do not involve using jQuery? (The client prefers not to use it) ...

Developing a TypeScript NodeJS module

I've been working on creating a Node module using TypeScript, and here is my progress so far: MysqlMapper.ts export class MysqlMapper{ private _config: Mysql.IConnectionConfig; private openConnection(): Mysql.IConnection{ ... } ...