Tips for validating user input in AngularJS without using a form tag

Within a popup, I am displaying HTML content that has been copied from another div and shown in the popup. I need to validate this input field to ensure it is required, and display an error message below the input box.

<!-- HTML code for changing zip code -->

<div class="hidden" id="updateZipContent">
    <div class="zipContent">
        <div class="padding-bt-2">Please enter a new zip code</div>
        <div class="row">
            <div class="text-left col-md-6 padding-bt-2">
                    <input ng-model="zipCode" type="text" class="form-control" maxlength="5" data-required="true" number-only>
            </div>  
            <div class="text-left col-md-4">
                <button class="btn btn-primary form-control">Update</button>
            </div>
        </div>
    </div>
</div>

The action for changing the zip code is implemented in autoQuotectrl.js

$scope.changeZipCode = function() {
    $rootScope.myModal = true;
    var firstDivContent = document.getElementById('updateZipContent');
    var secondDivContent = document.getElementById('dynamicContect');
    secondDivContent.innerHTML = firstDivContent.innerHTML;                        
}   

To keep other actions separate, a new controller utilityCtrl.js was created. This contains the action for hiding the popup.

$scope.closePopup = function () {
    console.log('here in utility');
    $rootScope.myModal = false;
    document.getElementById('dynamicContect').innerHTML = "";
}

How can validation be set up here? Click here for link to source

Answer №1

Check out the latest version of the code on this plunker.

One way to achieve this is by using the $compile directive.

$scope.changeZipCode = function()
                {
                    $rootScope.myModal = true;
                    var firstDivContent = document.getElementById('updateZipContent');
                    var secondDivContent = document.getElementById('dynamicContect');
                    var clonedElement = $compile(firstDivContent.innerHTML)($scope, function(clonedElement, scope) {
                      //attach the clone to DOM document at the right place
                      secondDivContent.innerHTML ="";
                      angular.element(secondDivContent).append(clonedElement);
                  });                        
                }

Answer №2

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

app.controller('MainCtrl', function($scope) {
  $scope.name = 'World';
});
<html ng-app="plunker">

  <head>
    <meta charset="utf-8" />
    <title>AngularJS Plunker</title>
    <script>document.write('<base href="' + document.location + '" />');</script>
    <link rel="stylesheet" href="style.css" />
    <script data-require="<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="fa9b949d8f969b88d49089bacbd4c8d482">[email protected]</a>" src="https://code.angularjs.org/1.2.25/angular.js" data-semver="1.2.25"></script>

  </head>

  <body ng-controller="MainCtrl">
    <div ng-form="myForm">
      <input type="text" required ng-model="user.name" placeholder="Username">
      
      <button ng-click="doSomething()" ng-disabled="myForm.$invalid">DO</button>
    </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

Cease the progress of a Sequelize promise within an Express.js application

Exploring the realm of promises is a new adventure for me, and I'm still trying to grasp their full potential in certain situations. It's refreshing to see Sequelize now supporting promises, as it greatly enhances the readability of my code. One ...

Having trouble with the Ng multiselect dropdown displaying empty options?

I'm currently facing a challenge in adding a multiselect dropdown feature to my project. Below is the code I have been working on: HTML <ng-multiselect-dropdown [settings]="searchSettings" [data]="dummyList" multiple> </n ...

Guide to adding a theme switcher feature to your current React website

Currently, I am faced with a challenge involving two theme files, theme.js and theme-dark.js, within the context of a complex React-based website. Despite having already set up the site, I am struggling to find a way to allow users to seamlessly switch bet ...

Error: Unable to access null properties while attempting to address Readonly property error by implementing an interface

Here is the code snippet I am working with: interface State { backgroundColor: boolean; isLoading: boolean; errorOccured: boolean; acknowledgment: string; } export class GoodIntention extends React.Component<Props, State> { ... onCli ...

"Discover the trick to adding and updating text in a URL using jQuery without needing to refresh the page

I successfully implemented pagination in WordPress using Jquery/Ajax/wp_pagenavi(). It works well as it only refreshes a specific div to load new content instead of reloading the entire page. However, I am looking to enhance this feature by updating a port ...

Add unique content to a div upon page reload

Whenever the page is refreshed, I would like to add a random anchor from an array into a specific div. Here's my current code: <div id="exit-offer" class="exit-offer-dialog"> <div class="offer-content" id="banner-load"> <bu ...

Getting the dimensions of an image using a path in JavaScript

I am trying to display a div with an image, its name, size, and download link using jQuery. Here is the code I have created: var image = 'image/example.png' $('#download').attr("href", result2); $('.image').attr("src", re ...

I'm encountering a npm error on Windows_NT 10.0.19042, does anyone know how to troubleshoot this issue?

After downgrading to [email protected], I encountered an error message that keeps popping up whenever I try to update npm or install new packages. What steps can I take to resolve this issue? npm ERR! Windows_NT 10.0.19042 npm ERR! argv "C:\ ...

Angular2 material dropdown menu

Currently, I am studying angular2 with its material design. One of the modules I am using is md-select for material and here is a snippet of my code: <md-select> <md-option value="1">1</md-option> <md-option value="2">2< ...

Is there a way to show the input value in a different form while still retaining the original value?

When receiving a pagination number from user input, I store it in a variable like so: $html .= "<input type='submit' name='next' value='$next_page_number' />"; Now, I'm looking to replace the displayed text for th ...

Subsequent pages are failing to load stylesheets

My HTML is not linking my CSS properly. I am using the Prologue template from html5up.com. In my main directory where index.html is located, I created a subfolder for the different products I want to display. This folder contains several files including 12 ...

issue with the emit() and on() functions

While diving into my study of nodejs, I encountered a puzzling issue where emit() and on() were not recognized as functions. Let's take a look at my emitter.js file function Emitter(){ this.events = {}; } Emitter.prototype.on = function(ty ...

Wait until all information has been entered into the database before replying to the request

I have been exploring a way to insert multiple data in one call and only trigger a response after all the data has been inserted. Here is my current implementation: create: function(req, res) { var response = {}; var num = req.body.num; var re ...

Ways to add more spacing between list items without affecting the position of the bottom div

I'm attempting to achieve a layout similar to an Instagram post, where the list expands but does not push the footer down. In my case, adding margin-bottom to the comment class affects the height of the <div class="post-details-container" ...

`Display communications using JQuery and C#`

I am aiming to create a messaging system on a website where users can send messages to each other. Each message will have a button that closes the message and updates the database to mark it as read. My main requirements include: The page should not rel ...

Adjust the checked state of the checkbox based on the outcome of the promise's data

Whenever the checkbox is clicked and the resolved data in a promise is false, I want the checkbox to remain unchecked. If the data is true, then the checkbox should be checked. I have set up a codesandbox for this purpose. This example utilizes react and ...

Using jQuery to loop through a collection

I have a page that displays a list of posts. When a user clicks on the show comments button for a particular post, the comments associated with that post become visible. This functionality is achieved by using this and then searching based on the click loc ...

Is there a way to superimpose multiple PNGs and ensure that each one is clickable within its designated area?

I am looking to implement a interactive image system for dynamically generated content. The image includes a background image and various grey-scale mask images. Background Image: (source: goehler.dk) Masks: (source: goehler.dk) , (source: goe ...

The site is visually appealing in Firefox, but has a few issues on Chrome

I've encountered a common issue where my website displays perfectly in Firefox but looks terrible in Dreamweaver and Chrome. To fix it, I made live CSS edits in Firefox then copied them to Dreamweaver resulting in a mess. Here's how it should lo ...

The Vue v-for directive encountered an unrecognized property during rendering

Trying to grasp the concept of v-for in Vue JS, especially since I am a newcomer to this framework. Since I am utilizing Django, custom delimiters are necessary. I have a script example that appends a list of objects to a data property: var app = new Vue( ...