Concealing/revealing placeholder text in Angular applications

Can anyone help me figure out how to display hint text below an input only if the input is error-free on $error? I've tried using ngShow/Hide and $valid/$invalid but it's not working as expected.

<div ng-form="reg.form" name="reg.form" novalidate>
   <md-input-container flex="100">
      <label>{{"views.application.mobile.label" | translate}}</label>
      <input type="tel" ng-model="reg.user.mobile" name="mobile" required
             ng-pattern="/(^04(\s?[0-9]{2}\s?)([0-9]{3}\s?[0-9]{3}|[0-9]{2}\s?[0-9]{2}\s?[0-9]{2})$)/">
      <div ng-show="???" class="hint">e.g. 0400123123</div>
      <div ng-messages="reg.form.mobile.$error">
        <p class="help-block" ng-message="required">{{"views.application.mobile.error.required" | translate}}</p>
        <p class="help-block" ng-message="pattern">{{"views.application.mobile.error.invalid" | translate}}</p>
      </div>
    </md-input-container>
</div>

Answer №1

To ensure the hint is displayed initially and validation errors kick in on blur, I recommend using a combination of $untouched and $error. When the field is "touched", the hint will continue to be displayed unless input is invalid. You can implement this as follows:

<div ng-show="reg.form.mobile.$untouched || (!reg.form.mobile.$error.required && !reg.form.mobile.$error.pattern)"
    class="hint">
    e.g. 0400123123
</div>

Answer №2

Check out this demonstration for assistance: http://plnkr.co/edit/lbiKfYbkZJWSu5oUmsAe?p=preview

If the field is left empty, an 'Error message' will appear; otherwise, a 'hint message' will be displayed. Below you'll find the corresponding HTML & JS code.

HTML:

<!DOCTYPE html>
<html ng-app="plunker">

  <head>
    <meta charset="utf-8" />
    <title>AngularJS Plunker</title>
    <link rel="stylesheet" href="style.css" />
    <script data-require="<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="2849464f5d44495a06425b6819061d0650">[email protected]</a>" src="https://code.angularjs.org/1.5.8/angular.js" data-semver="1.5.8"></script>
    <script src="app.js"></script>
  </head>

  <body ng-controller="MainCtrl">
    <form name="userForm" novalidate>
      <label>
        First Name: <br/>
        <input name="firstname" type="text" ng-model="user.firstName" required><br />
        <span class="error" ng-show="userForm.firstname.$error.required">Please enter First name<br /></span>
        <span class="hint" ng-show="!userForm.firstname.$error.required">Hint: First name cannot be left blank<br /></span><br />
      </label>
      <label>
        Last Name: <br/>
        <input name="lastname" type="text" ng-model="user.lastName" required><br />
        <span class="error" ng-show="userForm.lastname.$error.required">Please enter Last name<br /></span>
        <span class="hint" ng-show="!userForm.lastname.$error.required">Hint: Last name cannot be left blank<br /></span><br />
      </label>
      <button ng-click="submitUser()">Submit</button>&nbsp;<button>Cancel</button>
    </form>
    <pre>{{ user|json }}</pre>
  </body>

</html>

JS:

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

app.controller('MainCtrl', function($scope) {
  $scope.isSubmitted = false;
  $scope.submitUser = function() {
    $scope.isSubmitted = true;
  };
});

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 steps should be taken once the idToken in Firebase has expired?

My code is utilizing the onAuthStateChanged function: this.unregisterAuthObserver = firebase.auth().onAuthStateChanged(user => { if (user) { user.getIdToken(true).then((idToken) => { console.log(user) ... }); } After the idT ...

Tips for organizing and validating a collection of user-input responses using MongoDB and express

New to the world of React-Redux I'm working on a testing application where users can take tests. The tests consist of multiple choice questions, some with multiple answer options. (MERN Stack) Currently, I send a POST request every time an option is ...

Steps to extract the input value using Selenium IDE

What is the proper way to retrieve the value of the field "value" from an input using Selenium IDE? This value can vary, so I need to be able to recover it for reuse. Here is my input field: <input class="myClass" type="text" value="15" name="myNam ...

manipulating child element's innerHTML with javascript

Is there a way to change my icon from expand_more to expand_less in the code below? <li class="dropdown-bt" onclick="dropdown('content');"> <a>dropdown-content <i class="material-icons">expand_more</i></a> </ ...

Leveraging ng-class for selectively applying CSS3 animations based on conditions

When specific conditions are met in my controller, I apply two CSS3 animations to the DOM using ng-class. The animations (shake Y & shake X) are added based on certain criteria being satisfied. Here is a snippet of the relevant JavaScript code: $scope.sub ...

Is there a way to round a number in JavaScript with negative precision similar to the rounding function in Excel?

Is there a way to round the value 8904000 to 8900000 using Math.round? An example of this in MS Excel is shown below: =round(8904000,-5); ANS: 8900000 I attempted to use Math.round with a second argument, but it did not work as expected: Math.round(8904 ...

Secure your JavaScript file with encryption

I am curious if anyone has ever used a tool to protect and fully encrypt JavaScript files. I recently came across a tool that claims to be able to completely encrypt JS files. Have you heard of this before? What are your thoughts on it? ? ...

Retrieve the prior position using the AngularJS ui-router

Utilizing fromState and fromParams within the $stateChangeSuccess event allows us to access all details regarding the previous location. This concept is elaborated in the following discussion: Angular - ui-router get previous state $rootScope.$on('$s ...

The functions Show() and Hide() may not work in all scenarios within jQuery

I'm currently developing a website that allows users to participate in quizzes. Each quiz consists of 20 questions divided into three sections: 1 mark for 10 questions, 2 marks for 5 questions, and 4 marks for 5 questions. For each question, there are ...

Choosing the value in a dropdown menu depending on the property value of an object using the select and angular methods

When editing a product with a category, I want to display the current category in a dropdown. The user should be able to change the category if desired, but upon loading the page, I want to show the selected value of the current product. Below is the HTML ...

Apply a chosen style to the element that was clicked on, while removing the style from the rest

Here is an example of my ul li structure: <div id="categoryTree"> <ul> <li id="cat_15"> <a class="hasSubCat" href="javascript:void(0);"><img src="images/icons/folder.gif" border="0" alt="Folder" title=" Folder ">N ...

Error: The function is undefined and cannot be referenced

I have an "a href" tag that calls a function when clicked, but it's not working and I'm getting this error: Uncaught ReferenceError: Gonder is not defined index.php:10 onclick Here is the JavaScript code : <script type="text/javascript"> ...

Is there a framework available to animate Pseudo CSS elements?

Recently, I was working on developing a bar chart that utilized pseudo CSS elements (::before, ::after). While I successfully created bars that look visually appealing, I encountered a challenge when attempting to animate the height changes. Whenever I us ...

toggle classes using jQuery when a link is clicked

I'm currently working on a jQuery function that will apply a class to a selected link (which opens a page in an iframe) and then remove that class when another link is chosen. Previously, I received assistance from another member for a similar task in ...

"Challenges in Three.js: Solving Problems with Geometric Shapes and Internal

I'm trying to create a unique shape that resembles an open ring with squared edges instead of the traditional torus shape. I've experimented with using shapes and paths as holes in my design: var arcShape = new THREE.Shape(); arcShape.moveTo( ...

Removing an article from a Vue.js localStorage array using its index position

I am facing an issue while trying to remove an item from localStorage. I have created a table to store all the added items, and I would like to delete a specific article either by its index or ideally by its unique id. Your assistance is greatly apprecia ...

The onSubmit function is resistant to updating the state

Currently, I am facing a challenge while working on a form using Material-UI. The TextField component is supposed to gather user input, and upon submission, my handleSubmit() function should update the state with the user-entered information. Unfortunate ...

AngularJS dynamic data presents challenge in reloading Jquery data tables

Hey there, I'm currently using jQuery DataTable with AngularJS. You can find the reference site here: https://codepen.io/kalaiselvan/pen/rLoVkE While it works fine for static data, I encounter issues when trying to bind data from a database. T ...

'Invalid parameters' error triggered by bcrypt-nodejs - Passport

Recently I updated my user model in CoffeeScript for my Node.js app's login system: password: String changing it to: password: type: String select: false The function I use to compare password hashes with bcrypt is as follows: use ...

Utilizing Angular's promise rejection chaining method

When dealing with a chained promise and facing rejection in any of the promises, I require an async operation to be performed (such as retrieving a translated error message). Since chaining on rejection seems impossible when there is already a chained prom ...