Updating a validation directive on $watch in AngularJS version 1.2

I created a directive for validation on a multi-select that allows for dynamic length validation of selected items. The directive is used like this:

(function() {
    'use strict';

    angular
        .module('myModule')
        .directive('listLength', listLength);

    listLength.$inject = ['$parse'];

    function listLength($parse) {
        var directive = {
            require: 'ngModel',
            restrict: 'A',
            link: link
        };

        function link(scope, elem, attr, ngModel) {
            var length = 0;
            var exp = $parse(attr.listLength);
            if (exp.constant) {
                // Single value, no need to watch
                length = exp(scope);
            } else {
                // We have an expression, need to watch for changes
                scope.$watch(attr.listLength, function(newVal, oldVal) {
                    length = newVal;
                });
            }

            //For DOM -> model validation
            ngModel.$parsers.unshift(function(value) {
                if (!angular.isUndefined(value) && value !== "") {
                    var valid = value.length === length;
                    ngModel.$setValidity('listLength', valid);
                    return valid ? value : undefined;
                }
                return value;
            });

            //For model -> DOM validation
            ngModel.$formatters.unshift(function(value) {
                if (!angular.isUndefined(value) && value !== "") {
                    var valid = value.length === length;
                    ngModel.$setValidity('listLength', valid);
                }
                return value;
            });
        }

        return directive;
    }
})();

I am having trouble getting the validation to update properly when the expression (attr.listLength) changes. I attempted setting ngModel.$dirty to true but it did not work as expected.

Answer №1

Experiment with adjusting the watch parameter in this manner:

scope.$watch("listLength", function(newVal, oldVal) {
       length = newVal;
});

Answer №2

It seems that in Angular 1.2, the only way to achieve this is by using ngModel.$setViewValue. This method will activate all validation functions. For example, you can use the following code snippet:

scope.$watch(attr.listLength, function(newVal, oldVal) {
    length = newVal;
    ngModel.$setViewValue(ngModel.$viewValue);  // Setting view value to itself...
});

By doing this, it will trigger the validation functions. In versions of AngularJS 1.3 and above, you can accomplish this with ngModel.$validate()

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

Tips for concealing the sorting number in the grid header

I have implemented angularjs ui-grid for sorting 4 columns in my grid. However, I want to hide the sort numbers displayed in the grid. I have searched for a solution or configuration through API but did not find anything helpful. Thank you. https://i.sta ...

What could be causing my JavaScript function to produce repeated letters with just one key press?

After implementing a code that generates different variables based on the 'truth' variable, I encountered an issue. Everything works flawlessly when 'truth' is set to "name," but as soon as I switch it to "email," any keystroke results ...

What are some alternatives for integrating React production build files apart from utilizing Express?

Is there a way to integrate React into my library using the HTTP module? I'm trying to figure out how to recursively send static files. Specifically, I want to include the build folder from the React production build, but I'm not sure how to go a ...

JavaScript Ajax request lags significantly in Internet Explorer, while it executes instantly in Firefox

So I have this jQuery .ajax() call set up to retrieve a List<string> of IP addresses from a specific subnet. I'm using a [WebMethod] on an .aspx page to handle the request and ASP.NET's JSON serializer to format the response for my Javascri ...

What is the best way to convert an object into an array of objects for use in a select search functionality

I am attempting to map key and value pairs into a single array in order to use them as selectsearch options. I have successfully mapped each item individually, but now I need to combine all the data into one array. How can I achieve this? Here is how I am ...

Learn about generating PDF files with React Native Expo using the react-native-html-to-pdf library!

I'm currently attempting to execute a 'Hello World' code utilizing the react-native-html-to-pdf library in order to generate a PDF, but I am encountering difficulties setting it up in Expo. Would you be able to provide assistance? I have tri ...

Error not caught: [$injector:modulerr] Visit http://errors.angularjs.org/1.7.9/$injector/moduler for more information

I encountered an error in the console while loading my application. I am new to angular and any help would be greatly appreciated. I am attempting to export the datatable into excel, and I believe the issue lies with this line: angular.module('myApp& ...

How to verify changes in session variable using PHP and AJAX

Hey there! I'm looking for a way to continually monitor changes in a session variable within PHP. Let's say the session variable "x" starts off with a value of "1" and then, after five seconds, it changes to "2". This session variable "x" is up ...

Tips for creating a highly adaptable code base- Utilize variables

Can anyone help me optimize this lengthy and cumbersome code in HTML and JS? I want to make it more efficient by using variables instead of repeating the same code over and over. In the HTML, I've used href links to switch between different months, w ...

Trying to toggle between two Angular components within the app component using a pair of buttons

Currently, I am developing an application that requires two buttons to display different nested apps. Unfortunately, I am unable to use angular routing for this particular design. These two buttons will be placed within the app.component. When Button A i ...

Is there a way to identify and remove empty spaces and carriage returns from an element using JavaScript or jQuery?

Is there a way to easily remove empty elements from the DOM by checking if they contain only whitespace characters or nothing at all? I am attempting to use $.trim() to trim whitespace in empty elements, but some are still returning a length greater than ...

Strategies for transmitting computed variables from a controller to JavaScript once the computation is complete?

Within my application, I have a button that triggers an action called "method" present in the UserController. This particular action involves executing some specific tasks. def method ***performing necessary calculations and operations*** @my_variable ...

Utilize Redux Toolkit to efficiently share actions across different slices of state

How can I efficiently share common actions across multiple redux state slices? For instance, let's say I have an updateField action that I want to use in various slices other than just the profile slice. Should I import it from an external file for r ...

What is the best way to toggle the enablement of a textbox with jQuery?

Welcome all! Initially, all controls are disabled. Upon clicking the Add or New button, I want to enable textboxes and the Save button while keeping the Edit and Delete buttons disabled. Once the Save button is clicked, I wish to disable all textboxes and ...

TypeScript and Next.js failing to properly verify function parameters/arguments

I'm currently tackling a project involving typescript & next.js, and I've run into an issue where function argument types aren't being checked as expected. Below is a snippet of code that illustrates the problem. Despite my expectation ...

Instructions on inserting an IFRAME using JavaScript into dynamically loaded content via AJAX

How can I dynamically add an IFRAME using JavaScript to content that is refreshed via AJAX? Consider the following example: $('#bar').delegate('.scroll-content-item span a', 'click', function() { var object_id = $(this).p ...

It is advised not to use arrow functions to assign data when fetching API data with axios in Vue.js 2

Trying to retrieve data from a URL using Axios in my Vue app is resulting in the error message: Error: Arrow function should not return assignment Complete error message: Error: Arrow function should not return assignment (no-return-assign) at src\co ...

What are some ways to implement a pre-execution step, such as an interceptor, before Nextjs runs getStatic

When working with getStaticProps and getServerSideProps in Next.js, I need to intercept and add common header properties to all request calls that are executed server-side. axios.interceptors.request.use(function (config) { // Perform actions before ...

Get around operator precedence in JavaScript

Imagine having a string like this: '1 + 2 + 3 * 4' Can you solve it sequentially from left to right in order to obtain a total of 24, instead of 15? It's important to note that the string is unknown beforehand, so it could be as simple as ...

The JSON parsing functionality is not working as expected in my app.js file

app.js: const express = require("express"); const https = require("https"); const app = express(); const port = 3000; app.get("/",function(req,res){ const url ="https://maps.googleapis.com/maps/api/geocode/jsonaddress=1600+Amphitheatre+Parkway,+Mounta ...