I am eager to configure Angular's ng-pattern within a directive accompanied by its own template and scope for the purpose of form validation

I am working on a complex directive that requires its own scope, ngModel, and the replacement of the existing input. How can I make the directive include the ng-pattern attribute? In this example in jsFiddle, you can see that the validation does not change based on the input when the ng-pattern is added in the template. This project involves integrating with an existing application that already has numerous attributes on various input elements. My goal is to seamlessly add functionality to these existing input fields without causing any disruptions.

http://jsfiddle.net/MCq8V/

HTML

<div ng-app="demo" ng-init="" ng-controller="Demo">
    <form name="myForm" ng-submit="onSubmit()">
    <input lowercase type="text" ng-model="data" name="number">
    Valid? {{myForm.number.$valid}}
    <input type="submit" value="submit"/>
    </form>
</div>

JS

var module = angular.module("demo", []);

module.directive('lowercase', function() {
    return {
        require: 'ngModel',
        restrict: 'A',
        scope:{},
        replace: true,
        link: function(scope, element, attr, ngModelCntrl) {
        },
        template: '<input class="something" ng-pattern="/^\d*$/">',
    };
});

module.controller('Demo', Demo);

function Demo($scope) {
    $scope.data = 'Some Value';
}

Thank you for any assistance provided! Ideally, I would like to make minor adjustments to retain the ng-pattern, but it seems like I may need to handle the validation setup independently.

Answer №1

One way to incorporate the pattern attribute into an input item within a directive is by utilizing the compile function at the end of the link function. Instead of completely replacing the element's contents with a template, you have the option to directly modify the existing input tag.

        link: function (scope, element, attrs, formController) {

            // Determine appropriate template based on form field type
            var template = (scope.schema["enum"] !== undefined) && 
                           (scope.schema["enum"] !== null) ? 
                           $templateCache.get("enumField.html") : 
                           $templateCache.get("" + scope.schema.type + "Field.html");
            element.html(template);

            // Update attributes like type, ng-required, ng-pattern, and name
            if (scope.schema.type === "number" || scope.schema.type === "integer") {
                element.find("input").attr("type", "number");
            }
            element.find("input").attr("ng-required", scope.required);

            if (scope.schema.pattern) {
                element.find("input").attr("ng-pattern", "/" + scope.schema.pattern + "/");
            }
            element.find("input").attr("name", scope.field);

            // Compile the template against the current scope
            return $compile(element.contents())(scope);
        }

Answer №2

After experimenting with various approaches, I found that using a directive to replace an input with another input was causing Angular some confusion. Here is the solution I came up with: http://jsfiddle.net/MCq8V/1/

HTML

<div ng-app="demo" ng-init="" ng-controller="Demo">
  <form name="myForm" ng-submit="onSubmit()">
    <div lowercase model="data"></div>
    Valid? {{myForm.number.$valid}}
    <input type="submit" value="submit"/>
  </form>
</div>

JS

var module = angular.module("demo", []);
module.directive('lowercase', function() {
return {
    restrict: 'A',
    scope:{
        data:'=model'
    },
    replace: true,
    template: '<input class="something" ng-pattern="/^\\d*$/" name="number" ng-model="data" type="text">',
    };
});

module.controller('Demo', Demo);

function Demo($scope) {
  $scope.data = 'Some Value';
}

Furthermore, it's necessary to escape the backslash in the regex with another backslash.

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 dynamically adding an HTML element to index.html using JavaScript

https://i.sstatic.net/cAna8.png How can I use JavaScript to insert cards into a container or display them in flex? Currently, the cards are not displaying as desired. I attempted to insert data into the note class using insertAdjacentHTML in JavaScript, b ...

The code functions perfectly on JSfiddle, but for some reason it halts when implemented on

Unfortunately, the code that was working perfectly on JSfiddle seems to be encountering issues when implemented on a regular HTML site. The content loads fine but there seems to be an error with the preview function after selecting an image. We have colla ...

Failed to update the innerHTML attribute for the anchor tag

I'm attempting to apply styles through DOM manipulation using Angular's renderer2. I have successfully updated styles for all HTML elements except for anchors. In the example below, I am trying to replace the text www.url.com with World within ...

The Isomorphic-style-loader is throwing an error: "Cannot read property 'apply' of null"

Despite encountering the same error and exploring various solutions, I have yet to resolve my issue, potentially due to my limited understanding of the React structure. It seems that the error is stemming from context.insertCss.apply(context, styles) not ...

Creating multiple asynchronous calls within a loop in JavaScript

I am currently working on a task in my gulpfile.js that involves uploading an app using Gulp and SharePoint. 'use strict'; const gulp = require('gulp'); const build = require('@microsoft/sp-build-web'); const spsync = require ...

What is the best way to find a specific element value and gather all following elements in a

What is the best way to retrieve elements following -p or --name within this array? ['-p', 'player', '1', '--name', 'player1', 'name'] ...

The integration of Node.js and express.js from distinct JavaScript files

How can I utilize express.js to render html in two separate files? file1.js file2.js The code inside file1.js is as follows: var express = require('express'); var app = express(); app.get('/foo/bar1', (req, res) => res.json([&apo ...

Angular Material Slider is failing to display properly

I am struggling to get the Angular Material Slider to render correctly in my project. Here is the code I have been using: <div class="row formField" ng-cloak> <div class="col-md-2"> <div>送貨日期</div> & ...

The asynchronous functionality of Azure IoT Edge node SDK's invokeDeviceMethod seems to be malfunctioning

I am attempting to asynchronously return a result for a direct method call. This is what I attempted: const client = Client.fromConnectionString(process.env.AZ_IOT_CONNECTION_STRING); const methodParams = { methodName: "method", payload: 10, // Numbe ...

use javascript to navigate back to the parent window

When I open a new child window from the parent window, there is an HTML form in the child window for user input. Once the form is filled and submitted, the request is sent to the server. I want the response from the server to be redirected back to the pa ...

Exploring the nuances of receiving responses with NextJs, Nodemailer, and Fetch

Currently in the process of constructing a basic contact form with Next.js, nodemailer, and fetch. Despite successfully sending emails from the frontend form to the designated email account, the network shows the contact submission as pending. After approx ...

What could be causing ngInfiniteScroll to not work properly with tables?

I've been attempting to incorporate ngInfiniteScroll into my table using ng-repeat on <tbody> however, it isn't triggering when I reach the end of the page. <div infinite-scroll="list.getMoreItems()"> <table md-table md-row-se ...

Choose the fetched value from the options, or opt for the default value

Despite extensively reviewing the documentation and numerous questions here on SO, I am struggling to find a solution for my current issue. I have a dropdown that is populated with data from a database, and I am using ngOptions with the select as method to ...

Do you need to use jQuery with bootstrap or is it optional?

My experience so far has been primarily with the jQuery library, but I recently started delving into AngularJS. While I've gone through a couple of tutorials on Angular, I'm still uncertain about its specific advantages and when it's best t ...

Leveraging a script within a React component

Trying to implement a payment modal using a js script has led me to suspect that mounting it on the root div causes all components to unmount. I am looking for a way to conditionally load the modal so that users can cancel and open it later. const load ...

Utilizing Angular to Display Attachments from Domino Data Service

When retrieving a Domino Document using the /api/data/documents/unid/ syntax, I noticed that the attachment comes back encoded in base64 like this: "contentType": "application/octet-stream; name=\"Spitzbuben.docx\"", I am now looking for the be ...

Learn how to automatically select checkboxes in Vue.js based on database values when using Laravel

Being new to frontend development, I am facing some challenges with a specific issue. In my application, there is a "schedules" table which includes columns for "violation" and "remarks". The complexity arises when trying to loop through the remarks values ...

Refreshing the page when the hide/show button is clicked with jQuery

I have a situation where I am using jQuery to toggle the visibility of a div by clicking on show/hide buttons. However, I am facing an issue where the code does not work as intended. Every time I click the buttons, the div reverts back to its original stat ...

the attempt to substitute an image with a canvas is unsuccessful

I attempted to utilize a function that transforms images into canvas elements. In my approach, I aimed to swap out the generated canvas with the corresponding image by using jQuery's .replaceWith() method, but unfortunately, the process did not yield ...

using an object's key as a variable in JavaScript

Is it possible to reference an object's key as a variable and then modify its value? I am experimenting with the following: const obj = { x: { y: { z: 'test' } } } const func = () => { let root = obj['x'] ...