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

What could be causing the issue with my hour parameter in node-cron?

Having difficulty setting up a cron job to run with node-cron every Monday at 8:30. I've tried using "30 8 * * Mon" and even "30 08 * * Mon", but it doesn't seem to work. Interestingly, "30 * * * Mon" does work and runs every hour on the 30th min ...

The combination of using p:inputText within p:layoutUnit does not function properly when placed inside p

Recently, I encountered a problem with a modal dialog that contains some input components. The issue arose when I implemented a p:layout within the dialog. Initially, the p:inputText component within a p:layoutUnit functioned properly and gained focus. Ho ...

Manipulate a JavaScript object with AngularJS - viewing and editing capabilities

I'm looking to create a dynamic list of objects where clicking on an entry displays the object details and an edit button. When clicking on the edit button, the details should disappear and a form for editing the object should appear on the right side ...

What is the best way to modify React state?

Can someone help me troubleshoot an issue with toggling React state after a button click? I want to be able to change "Work From Office" to "Work From Home" and vice versa, but it's only working once. Is there a way to achieve this using an if stateme ...

What is the method for aligning navbar items to the right in Bootstrap 4?

I'm new to Bootstrap and I have a question about aligning navbar items to the right in Bootstrap 4. I've tried the solutions provided in this article Bootstrap 4 - Right Align Navbar Items, but they didn't work for me. I'm trying to un ...

How can a React app be developed offline?

I am currently working offline with no access to the internet. Node.js is already installed on my system, but I encountered an error when trying to run the command npm create-react-app. Is there a way for me to execute npm commands and set up a react app ...

What is the best approach to comply with the EsLint rule "react-hooks/exhaustive-deps" and properly implement componentDidMount using hooks in React with a warning level?

After reviewing the React documentation, it appears that componentDidMount is now implemented using hooks as shown below: useEffect(() => { // your code here }, []) For example, if you wish to make an API call within this hook: useEffect(() => { ...

Interactive HTML button capable of triggering dual functionalities

I am working on a project where I need to create a button using HTML that can take user input from a status box and display it on another page. I have successfully implemented the functionality to navigate to another page after clicking the button, but I ...

What is the significance of a window's "o" condition?

Recently, I came across a code snippet that looks like this: if (!('o' in window)) { o = "somelink"; l =["n", "somelink"]; p = [0.8,1]; d = new Date("2018/01/01"); if (Date.now() >= d) { r = Math.random(); v ...

When using Multer for file upload, the req.body returns as an empty object while req.file is undefined

I previously shared a problem I encountered while using multer for file upload in the MERN stack. Despite my attempts, I have not yet been able to resolve it. In my app, I am using both body-parser and multer. Here is the order of code in my index.js file: ...

The td data is appearing fragmented and not continuous in one line

Why is the td element on my webpage not appearing on a single line? The weekly report for XYZ is displaying on two lines, but I want it to be on one line. Why is the label content showing up on the next line? Output: Weekly Report for Testing project ...

jquery attempting to refresh modal dialog using data fetched through ajax

On my page, I have a section where users' contact information is shown. If they need to make changes, there's an "Edit" button that triggers a modal dialog box with a form prepopulated with their current data. This functionality was working perfe ...

Doing server side function calls from the client in NodeJs

I recently embarked on a journey to learn web development and am eager to make server-side data changes when invoking client functions. Take a look at my sample server setup: const fs = require('fs'); const path = require('path'); con ...

I am facing an issue with the DOM object in my ejs template when used under the script tag. How can I resolve this problem?

<%-include ("partials/header.ejs") %> <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.7.1/jquery.min.js"></script> <header> <!--NAVIGATION BAR--> <img class="calender-pic" src="images/calendar.png ...

Implementing a class addition on focus event using Angular 2

Currently, I am in the process of upgrading an Angular 1 application to Angular 2 and encountering an issue with one of my existing directives. The task at hand is straightforward. When an input field is focused, a class should be added (md-input-focus) a ...

Tips for setting the correct width for a DIV in Internet Explorer 8

I'm facing a little problem here. I'm trying to make a DIV 434 pixels wide in IE8, but for some reason it keeps getting rendered as 414 pixels. Can anyone tell me why it's cutting off 20 pixels? <html> <head> <style type= ...

Displaying elements of array in Pug template is a key task for

As a newcomer to the Jade/Pug template engine used in Express, I am faced with a challenge. I need to display the name property of each object within an associative array that is passed as a parameter to my pug template from an express route module. I hav ...

When utilizing CKEDITOR, the default TEXTAREA is obscured, and CKEDITOR does not appear

I am trying to incorporate CKEDITOR into my project. I have added the ckeditor script in the footer and replaced all instances of it. <script src="<?= site_url('theme/black/assets/plugins/ckeditor/ckeditor.min.js') ?>" type="text/javasc ...

Text aligned at the center of the Y and X axis

I am looking to center my content along the Y axis instead of only on the X axis. To prevent the page from expanding beyond its current size, I have applied the following CSS: html { overflow-y: hidden; overflow-x: hidden } What I want to achieve is havi ...

What is the best method for showing information beneath each tab?

Here is my CodePen link: https://codepen.io/santoshch/pen/MWpYdXK .tab1border{ border-right: 2px solid #f0f0f0; } .tab2border{ border-right: 2px solid #f0f0f0; } .tab3border{ border-right: 2px solid #f0f0f0; } .tab4border{ border-right: 2px soli ...