The combination of form validation and an isolated directive is causing the deletion of the scope value

When combining a directive with isolate scope and custom validation, the validation process changes my scope value to undefined if the validation fails.

You can view the code in this jsfiddle link: http://jsfiddle.net/5mKU3/7/

The HTML structure is as follows:

<div ng-app="myApp">
    <div ng-controller="example">
        someModel: {{someValue}}<br>
        <input type="text" isolate ng-model="someValue" validate />
    </div>
</div>

The JavaScript implementation is outlined below:

angular.module('myApp', []).directive('isolate', function () {
    return {
        require: 'ngModel',
        scope: {}
    };
}).directive('validate', function () {
    return {
        require: 'ngModel',
        link: function (scope, element, attrs, ctrl) {
            ctrl.$parsers.unshift(function (value) {
                value = value || '';

                if (value.length < 10) {
                    ctrl.$setValidity('fail', true);
                    return value;
                } else {
                    ctrl.$setValidity('fail', false);
                    return undefined;
                }
            });
        }
    };
}).controller('example', function ($scope) {
    $scope.someValue = '1234';
});

If the input exceeds 10 characters, the validation will fail. Is there a way to prevent the $scope.someValue from being set to undefined when validation fails?

Note that the angular version used in this scenario is 1.2.18.

Answer №1

To enable invalid values, set ngModelOptions.allowInvalid to true.

An example of your input would be:

<input type="text" isolate ng-model="someValue" validate ng-model-options="{allowInvalid:true}" />

For more information, refer to the description of the $validate() method

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 is the best way to determine in component.html whether the column type is equal to 1 to show the label text "Active,"

Having trouble checking the value of an object named ReportControl. If the column type is 1, display the label "active"; otherwise, display the label "not active" on reportcomponent.html. The data for the ReportControl object is as follows: {"reportId": ...

Warning in React: You cannot use functions as a child element

My React component is causing issues with rendering and giving me a persistent warning The error message reads: "Functions are not valid as a React child. This may happen if you return a Component instead of from the render function. Or maybe you meant t ...

Adding names in real time to a list within a template

I am currently facing an issue while attempting to dynamically add and populate values in an array. Strangely, I am unable to see any output from a console.log statement. This has left me perplexed as to why there are no errors or logs being displayed. Co ...

Utilizing Mysql Joins with parameterized queries in Node.js: A Comprehensive Guide

Currently, I am utilizing Node.js and Express.js for my project. In particular, I am incorporating the "mysql2 library" into my development process. My current task involves concatenating and joining queries with parameters in a secure manner. How can I ...

Make sure to verify if all values are contained within an array by utilizing JavaScript or TypeScript

These are the two arrays I'm working with. My goal is to ensure that every value in ValuesToBeCheckArr is present in ActualArr. If any values are missing from ActualArr, the function should return 0 or false. Additionally, there is an operator variabl ...

JQuery Mobile's collapsible content blocks with dynamic functionality are experiencing issues with expanding when using Spry

I'm feeling lost here! I know this is a FAQ, but I can't seem to find a simple enough example that explains it clearly for someone like me. Issue I have created a JQM page that gets populated with data from Spry. The layout of the page looks goo ...

Linking Elements in Angular Framework

I'm currently working on a website using Angular that is set up as a Multi-Page Application (MPA). Each page is a separate component that I have developed, but I'm unsure how to connect them together. I want users to be directed to different page ...

Using jQuery, how can I add value to every input when the option is changed?

I need help changing the values of all input:text elements based on selections from a select menu. Specifically, I want to change only the matched td.class values from the data-pset attribute inside the <select>. As a beginner in jQuery, I can only ...

Retrieve pairs of items from a given variable

Containing values in my 'getDuplicates' variable look like this: getDuplicates = 100,120,450,490,600,650, ... These represent pairs and ranges: Abegin,Aend,Bbegin,Bend My task is to loop through them in order to apply these ranges. var ge ...

What are the drawbacks of heavily relying on AngularJS and JavaScript in website development?

Currently, I am in the process of developing a large-scale project. This entails creating a dynamic webshop where a majority of the components are generated dynamically. To achieve this, I have opted to utilize the AngularJS framework and incorporated the ...

Using CSS to mask images with border-radius

I am currently designing a website for a friend, and I have encountered an issue with an image that I have masked using CSS border-radius. The image is larger and taller than its container, so I used JavaScript to center it correctly. However, it appears ...

Angular FB Share without requiring a Backend

Limitation: My only option is to upload html/css/js directly to the server through our client. I am attempting to share content on Facebook without a backend in AngularJS. I need meta tags to achieve this, but I also need to display different content base ...

html displaying dynamic data in a table

As a beginner in coding, I am attempting to create a dynamic table. The first column is working fine with each new cell being added to the top. However, when I try to add columns, they fill from top to bottom instead of mirroring the first column. I want m ...

Sentry platform is failing to record network-related problems

Incorporating Sentry into my Next.JS application has allowed me to easily detect JavaScript errors such as reference or syntax issues on the Sentry platform. Unfortunately, I have encountered some challenges as Sentry is not logging any network-related er ...

Retrieve the value of the element and combine them together (The parseFloat function may not work as expected

The following code is what I am currently working with: var num1=$("#num1").val(); //the num1 value is 12.60 //html code for this number <input id="num1" value="12.60" /> num1=parseFloat(num1).toFixed(2); var num2=$("#num2").text(); //the num2 valu ...

Is it possible to incorporate Vue and Vuetify into an existing project that requires IE compatibility?

Currently in the process of enhancing a legacy project with new functionality. The front end is currently relying solely on jQuery for all the webpages. I have been tasked with adding another webpage and would like to incorporate Vuetify + Vue due to the i ...

What might be causing the image links to malfunction on the server while functioning normally when offline?

Recently, I've been working on a website and after successfully testing it offline, I decided to put it online. However, I've run into an issue where some images are not showing up. What's even stranger is that the images that are appearing ...

Angular material table cell coloring

Here is my current setup: I have an array of objects like this: users : User []; average = 5; compareValue (value){ ...} And I am displaying a table as shown below: <table mat-table [dataSource]="users"> <ng-container matColumnDef= ...

Troubleshooting a setTimeout filter problem in Vue

Implementing a notification system in Vue has been my latest project. I've created a Notifications component to store error messages that I want to display. data(){ return { alerts: { error: [] } ...

The ng-show directive in AngularJS seems to be malfunctioning when used within a modal

Upon clicking a button, I am opening a modal popup where I want to display a progress bar. However, the progress bar is not showing up the first time the popup opens; it only appears after closing and reopening the popup. Here is the controller code that ...