Exploring the benefits of utilizing ng switch for more effective validation

Visit this link to see the code

My goal is to display error messages one after another. I am considering using ng switch instead of ng:show for better efficiency, but my current approach is not working as expected.

<div class="errorDiv" ng-switch on="true">
    <div ng-switch-when="form.LastName.$error.required" style="color: white; background-color: red">This field is required</div>
    <div ng-switch-when="form.LastName.$error.len" style="color: white; background-color: red">Invalid length</div>
    <div ng-switch-when="form.LastName.$error.dallas" style="color: white; background-color: red">Error: Dallas</div>
</div>

Answer №1

The logic for ng-switch is the opposite of what you have. The expression to evaluate should be in the on attribute, while the values to match should be within the when attributes. If you prefer a different approach, consider this revised example:

<div class="errorDiv" ng-switch on="form.LastName.$error.required">
    <div ng-switch-when="true" style="color: white; background-color: red">required</div>
</div>
<div class="errorDiv" ng-switch on="form.LastName.$error.len">
    <div ng-switch-when="true" style="color: white; background-color: red">len</div>
</div>
<div class="errorDiv" ng-switch on="form.LastName.$error.dallas">
    <div ng-switch-when="true" style="color: white; background-color: red">dallas</div>
</div>

http://jsfiddle.net/AbmsG/3/

Answer №2

There are multiple reasons why this code snippet may not produce the expected results.

The issue lies in the usage of ng-switch-when, as it requires a string comparison. This means that the comparison is made with the literal string "form.LastName.$error.required", not the value of the object property with the same name.

On the other hand, ng-switch expects an expression to evaluate. In this case, only if the expression resolves to true (as a string "true") will the corresponding case be matched.

This alternative approach can be used to achieve similar functionality:
<div class="errorDiv" ng-switch on="form.LastName.$error.required">
    <div ng-switch-when="true" style="color: white; background-color: red">required</div>
</div>
<div class="errorDiv" ng-switch on="form.LastName.$error.len">
    <div ng-switch-when="true" style="color: white; background-color: red">len</div>
</div>
<div class="errorDiv" ng-switch on="form.LastName.$error.dallas">
    <div ng-switch-when="true" style="color: white; background-color: red">dallas</div>
</div>

Answer №3

According to dnc253, your implementation of the ng-switch logic is not correct. The solution provided below will help you achieve the desired functionality.

http://jsfiddle.net/ud3323/AbmsG/7/

HTML

<form ng-app="someApp" name="form" ng-controller="MainCtrl">
  <input validate name="EmailAddress" ng-model="form.emailAddress" john len = "8" required />
  <div class="errorDiv" ng-switch on="currentError">
    <div ng-switch-when="required" style="color: black; background-color: yellow">required</div>
    <div ng-switch-when="len" style="color: black; background-color: yellow">len</div>
    <div ng-switch-when="john" style="color: black; background-color: yellow">john</div>
  </div> 
</form>

JS

angular.module('someApp', [])
  .directive('validate', function() {
  return {
    require: 'ngModel',        
    link: function(scope, element, attrs, ctrl) {
      element.bind("keydown keypress", function(event) {
          if (event.which === 13) {
              scope.$apply(function() {
                  scope.$eval(attrs.onEnter);
              });
              event.preventDefault();
          }
      });
      ctrl.$parsers.push(function(value){
          if (!value) value = '';
          ctrl.$setValidity('required',
                             value != '');
          ctrl.$setValidity('len',
                              value.length == 8);
            ctrl.$setValidity('john',
                   value=='john');
            return value;
        });
    }
}
}).controller('MainCtrl', ['$scope', function ($scope) {
  $scope.$watch('form.$error', function (errorObject) {
    if (errorObject.required) $scope.currentError = "required";
      else if (errorObject.len) $scope.currentError = "len";
      else if (errorObject.john) $scope.currentError = "john";
  }, 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

React, Storybook - Error TS2307: Button module not found or its type declarations. Can Storybook resolve this issue?

In my React project, I have a Button component created with "create-react-app" that uses absolute paths for importing. When trying to import { Button, ButtonProps } from 'Button', I encountered an error with TS2307. The absolute path 'Butto ...

Code not functioning properly in Internet Explorer

In one of my JavaScript functions, I have the following CSS line which works well in all browsers except for IE (Internet Explorer). When the page loads, the height of the element is only about 4px. element.setAttribute('style', "height: 15px;") ...

Try implementing toggleClass() in the accordion feature rather than addClass() and removeClass()

Hey there! I've implemented accordion functionality using the addClass() and removeClass() methods. Here's a breakdown of what I did: <div class="container"> <div class="functionality">Accordion</div> <ul class="acco ...

AngularJS controller updating only a portion of the dataset

My small bottle server is capable of returning random values based on a specific machineID. Here's how it works: @app.route('/dataMachine') @enable_cors def simulatedMachineData(): prevVals = {'machineID_1': 0,'machineID ...

Navigating a variety of page styles and views in Angular 1 using routing

Following a tutorial, I have set up code that routes to various pages related to the main type of document used in the application: angular.module('loc8rApp', ['ngRoute', 'ngSanitize', 'ui.bootstrap']); function ...

Retrieve the ultimate content of a text field when a key is pressed, only if the click action is permitted to proceed

Is there a method to prevent users from entering certain characters into a text box based on the resulting text in the textbox? One possible approach is outlined below: <input type="text" id="test" /> document.getElementById(&qu ...

Unexpected behavior is being encountered with the else statement, and there are compatibility issues with IE and Mozilla Browser in the overall script

Script is functioning as expected in Google Chrome, but is not responsive in IE and Mozilla browsers JavaScript code: <script src="jquery.min.js"></script> <script> function Run() { if(jQuery('#inputtext').val() == '0 ...

What is the process for creating a parent container in which clicking anywhere inside will cause a child container (built with jQuery UI draggable) to immediately move to that location?

This is a rundown of tasks that I am struggling to code more effectively: When the bar is clicked anywhere, I want the black dot button to instantly move there and automatically update the displayed percentage below it. Additionally, when I drag the butt ...

Interact with the button through Swipe Left and Right gestures

Is it possible to trigger a button click using JQuery or JavaScript when swiping left or right on two buttons like these? <button id="right" type="button">SWIPE RIGHT</button> <button id="left" type="button">SWIPE LEFT</button> If ...

"Exploring the relationship between Typescript and Angular: transforming variables within different

Ever since I made the switch from JavaScript to TypeScript (Version 2.1.5), I have been facing an issue with the code that filters date selection. Despite my efforts, I haven't been able to find a good fix for it yet. Here are the two date-pickers: F ...

Creating an illuminated atmosphere: How to place a light source within a container using ThreeJS

Attempting to replicate the luminous box from Beat Saber in ThreeJS: https://i.sstatic.net/6IUmp.png Initiated by crafting a shape in Blender and exporting an OBJ. Imported it into Three, simply as geometry: https://i.sstatic.net/BGA1n.png Subsequently ...

Create a copy of a div element once the value of a select element has

After modifying a select option, I'm attempting to replicate a div similar to the example shown in this link: http://jsfiddle.net/ranell/mN6nm/5/ However, instead of my expected lists, I am seeing [object]. Any suggestions on how to resolve this issue ...

Abbreviating Column Labels in Google Visualization

Is there a way to use the google visualization API to display column headers in an abbreviated form in a table, but show the full labels in a pie chart using the same dataset? Check out this snippet of JavaScript: //create the dashboard and table chart ...

Obtaining the responseJSON property from a jQuery $.ajax object involves accessing the data returned

Recently, I encountered an issue with my JavaScript code that involves an AJAX request: $ajax = $.ajax({ type: 'GET', url: 'DBConnect.php', data: '', dataType: 'json', success: function(data) {} ...

The challenge with the mousewheel function in THREE.js Editor

Attempting to create a basic scene in the THREE.js Editor. Using the built-in Script editor, all control functions seem to be functioning correctly except for the mousewheel (I've tried mousedown, mousemove, etc.). I even attempted to add a listener ...

AngularJS ng-bind-html is a powerful feature that enables bi-directional data binding within

I am facing an issue with my AngularJS app where I am fetching data from a webservice and trying to bind it to the template using ng-bind-html. However, when attempting to bind the data inside ng-bind-html, nothing seems to happen. Can anyone help me with ...

Is the custom attribute event being triggered too soon?

My Unique Component Creation Journey I have meticulously crafted a custom component to enhance the navigation of my application. The core structure consists of an ul element, with each li item dynamically generated based on the contents of the router&apo ...

What is the best method for choosing the parent elements?

I am attempting to create a sidebar that saves the last clicked link in local storage and still displays the collapsed links after the page is reloaded. $(".clickedLink").parent().parent().css('background-color', 'green'); Ca ...

Using the `find()` method in a loop of Mongoose iterate

Searching for documents based on conditions stored in an array can be quite useful. Take this example: subscriptions=[ {teacher: 'john', student:'david' ,course:'math'}, {teacher: 'john', student:'david' , ...

No changes occur within this JavaScript code

I am currently working on a piece of Java Script code: document.onreadystateChange = function() { if (document.readystate === "complete") { var menu = document.getElementsByClassName('menu'); var b0 = menu[0]; b0.addE ...