Troubleshooting issues with AngularJS ng-fab-form server errors

Validation is being used on both the AngularJS side and server side to check for duplicate values, and I want to show these errors to users. Previously, without using ng-fab-form, I created a custom server error directive and implemented it like this:

<input type="number" id="level" name="level" ng-model="vm.record.level"
  server-error
  required>
<div ng-messages="vm.form.role_level.$error">
  <p ng-message="server">{{ vm.errors.level }}</p>
</div>

However, the main purpose of the library is to eliminate this repetitive process. With the use of "Controller as" syntax, I assign errors to each field when there are issues saving or updating the model:

angular.forEach(result.data.errors, function (errors, field) {
  vm.form[field].$setValidity('server', false);
  vm.errors[field] = errors.join(', ');
});

I have customized the validation template to display messages for server errors, but I am struggling to show dynamic error text. It seems to be related to scope inheritance. Any suggestions on how I can achieve this desired effect?

Answer №1

Here is a way I discovered to achieve this:

Include a custom attribute to store the server error message and keep an eye on any errors.

<input type="number" id="level" name="level" ng-model="vm.record.level"
  validation="{{ vm.errors.level }}
  server-error
  required>

In the validation template, show the value of the attribute.

<li ng-message="server">{{ attrs.validation }}</li>

Answer №2

Consider utilizing $asyncValidators over $setValidity from [email protected].

app.directive('username', function($q, $timeout) {
  return {
    require: 'ngModel',
    link: function(scope, elm, attrs, ctrl) {
    var usernames = ['Jim', 'John', 'Jill', 'Jackie'];

      ctrl.$asyncValidators.username = function(modelValue, viewValue) {

        if (ctrl.$isEmpty(modelValue)) {
          // consider empty model valid
          return $q.when();
        }

        var def = $q.defer();

        $timeout(function() {
          // Mock a delayed response
          if (usernames.indexOf(modelValue) === -1) {
            // The username is available
            def.resolve();
          } else {
            def.reject();
          }

        }, 2000);

        return def.promise;
      };
    }
  };
});

(excerpt sourced from the documentation)

You can easily include the message in your custom validations template as follows:

angular.module('exampleApp', [
    'ngFabForm'
])
    .config(function (ngFabFormProvider)
    {
        ngFabFormProvider.extendConfig({
            validationsTemplate : 'path/to/your-fabulous-validation-template.html'
        });
    });

And within the template, add:

<li ng-message="username">I'm not valid!!! ;(</li>

An related issue was documented on the module's github page: https://github.com/johannesjo/ng-fab-form/issues/34

To improve this solution further, an interface is needed. While it currently doesn't exist, you have the option to raise an issue for consideration.

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

Ensure that the headers of the table are properly aligned with the

Here's the code snippet I'm currently working with: function deleteRow(row) { var i = row.parentNode.parentNode.rowIndex - 2; // this -> td -> tr // -2 because the first 2 rows are used for header var tbl = docu ...

Utilizing a static method from a Class imported from a Node.js module

One puzzling question arises: How can we reference other static methods from within a static method of a class exported from a NodeJS module? Let's consider the following scenario. We have two modules: test1.js var Parent = class { static smetho ...

Trigger an Ajax function using a button within a Bootstrap modal

I need to trigger an ajax function after selecting an option from a bootstrap confirmation modal. The modal will appear by calling the remove(parameter) function. Any assistance would be greatly appreciated function remove(parameter){ // $("#remove-mod ...

The function loops through an array of objects and combines specific properties from the objects into a single string

I am currently working on creating a unique custom function that will loop through an array of objects and combine selected object property keys into a single string separated by commas. Let me explain using some code: var products = [ { "id": 1, ...

Node.js web server becomes inactive when not actively used

I have set up a basic express https web server on my Windows 10 machine to serve my local network. Initially, the server is able to connect with all devices on the LAN without any issues. However, after a few minutes, it appears to go idle and stops respon ...

When trying to access the Nodejs http://test.dev:3000/api/profile API, I encountered an issue where there was no 'Access-Control-Allow-Origin' header for the Origin 'http://localhost:9000'

NodeJS - Angularjs Encountering a CORS Issue in NodeJS. While REST GET requests are functioning properly, I'm facing an issue with REST POST requests in nodeJS and unable to resolve it. Upon making the request, I am receiving the common error messa ...

What is the best way to choose an item from a dropdown menu using JavaScript?

Is there a way to set the dropdown value from the client side? Currently, I am loading countries and states using a countries.js file on grid row selection for updating. However, because it is loaded from the client side, I am unable to load country and st ...

I am encountering a situation where the model.findOne() method in my Node.js application is unexpectedly returning null, despite the

My goal is to verify if the user already exists in the database. I have set up a system where, on the client side, I use a JavaScript function to send the user's email ID to a Node.js route. This route then checks if the user exists in the database or ...

Changing the bootstrap popover location

I'm looking to customize the position of a Bootstrap popover that appears outside of a panel. Here's my setup: HTML: <div class="panel"> <div class="panel-body"> <input type="text" id="text_input" data-toggle="popover ...

Efficiency of Promise-based parallel insert queries in MySQL falls short

I have developed a code in Node.js to execute insert queries using Promise.js but unfortunately, I am encountering an exception stating "Duplicate Primary Key" entry. Here is the snippet of the code: var Promise = require("promise"); var mySql = requir ...

The JQuery function .load() is not functioning correctly

How can I dynamically load a webpage's content into a div using JavaScript and jQuery? Here's what I have tried: <script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js"></script> When a s ...

Tips for accessing session values in client-side code without echoing them out

Is there a way to access the session['something'] value in my JavaScript code without displaying it somewhere on the page? I have discovered two possible solutions so far: 1) Utilize the hidden field trick. 2) Implement AJAX. Note: My session d ...

Utilize data from two distinct JSON sources that are updated at varying intervals, and display the combined results in an ng-repeat

I am currently working on creating a status list that pulls data from two separate JSON sources. The main purpose of this list is to show general information from the first source, while also indicating a status color based on the number of people in the s ...

Promise rejection caused by SyntaxError: Unexpected token i found in JSON at position 0 while trying to fetch a raw file from Gitlab

I'm attempting to retrieve a raw file from a Gitlab repository by following the official documentation. Here are the functions in question: methods: { async getProjects(url, method, payload) { const token = this.$store.getters.token ...

What is the best way to incorporate the ion scroll directive into a div element?

I am currently working on implementing this example in the Ionic framework. I have been using the following code snippet from this link: http://plnkr.co/edit/LjAoAPFDx0eVPkx3dKfu?p=preview. The problem I am facing is that even though there are only six ele ...

The Vuetify treeview displayed all objects as open, even though I had not enabled the "open-all" option

Currently, I am configuring Vuetify's treeview component for my project. When I clicked on the folder objects within the treeview, every object opened up without me setting the 'open-all' option. My project is based on vue cli 3 and my ESLi ...

Playing back an Audio object using JavaScript

I'm facing an issue with replaying an audio sound every time the game starts in my Cocos2d javascript code. The sound plays correctly the first time, but subsequent attempts to play it result in no sound being heard. Below is my code snippet: var my ...

Enhance efficiency of repetitive tasks involving accessing the Mongo database

Currently, I am developing a chat bot using MeteorJS/NodeJS, which engages with approximately 2,000 active users on a daily basis. Tracking the number of individuals who interact with the bot each day is made possible by storing their activity information ...

Using AJAX to send a POST request with an array

My issue is that when using jQuery.ajax to post data to an action page, I am encountering a problem with the variable arrControlls. jQuery.ajax({ type: "POST", url: "../ajax/si-notificar_investigacion.php", data: { idincidente: $("#idi ...

Angular ensures that the fixed display element matches the size of its neighboring sibling

I have a unique challenge where I want to fix a div to the bottom of the screen, but its width should always match the content it scrolls past. Visualize the scenario in this image: https://i.sstatic.net/i7eZT.png The issue arises when setting the div&apo ...