Using external directive to validate Access Form

As a newcomer to angular, I have created a form with validation that only enables the save button when the validation pass

<input type="submit" value="Save" ng-disabled="!frmRegister.$valid" />

I implemented a directive to handle global form submission.

app.directive('mysavebtn',function(){
            return {                
                restrict : "E",
                scope :{
                },
                controller : function($scope){

                },
                link : function(scope,elem,attr){

                },
                template : '<div style="clear:both;" >'
                 +'<input type="submit" ng-disabled="!frmRegister.$valid" value="Directive Save"  />'
           +'</div>'
            }
        });

However, the Directive save button remains disabled even when the form is valid! Note: I placed the save button inside the form for validation purposes

You can view a working example here

How can I access Form validation from the mysavebtn directive? Please provide guidance.

Answer №1

To incorporate the form validity state into an isolated scope within your directive, you can utilize the '=' notation for two-way binding. To achieve this, adjust the HTML of your directive as shown below:

<mysavebtn form-valid="frmRegister.$valid"></mysavebtn>

Additionally, modify your JavaScript code as follows:

app.directive('mysavebtn', function() {
  return {
    restrict: "E",
    scope: {
      formValid: "="
    },
    controller: function($scope) {

    },
    link: function(scope, elem, attr) {

    },
    template: '<div style="clear:both;" >' + '<input type="submit" ng-disabled="!formValid" value="Directive Save"  />' + '</div>'
  }
});

As a result, the form validity status will be accessible within the directive's template through the formValid variable. Take a look at the functioning PLNK. For more in-depth information, refer to Angular's directive guide.

Answer №2

To improve communication between directives, one effective method is to utilize the require keyword to connect to another directive controller (specifically the form directive in this instance).

I have made some modifications to your plnkr: http://plnkr.co/edit/rGxmu7M33Ftb52MobzdK?p=preview

app.directive('mysavebtn', function () {
  return {              
    restrict: 'E',
    require: '^form',
    scope: {},
    link: function(scope, elem, attrs, formCtrl) {
      scope.formCtrl = formCtrl;
    },
    template: '<div style="clear:both;">' +
      '<input type="submit" ng-disabled="!formCtrl.$valid" value="Directive Save"  />' +
    '</div>'
  }
});

Insert your mysavebtn component inside a form element to establish a connection. This allows access to the complete form API and opens up additional possibilities.

By the way, creating a binding for this is not required as mentioned in the previously accepted solution.

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

Is there a way to eliminate a specific input box using the jquery remove function?

I've been working on some code and have run into an issue. Currently, the remove function only works on one input box that is created with the append function. I would like it to be able to work on every input box generated through the append function ...

How can I extract an array of objects from an array of arrays containing objects?

Here is the array I am currently working with: let findAllSegmentProjectMediaFilesXref = [ { it: 0, bt: 0, items: [ { mute: false, startPosition: 10, endPosition: 20, ...

Searching for documents in MongoDB using a reference field

I'm working with two Mongo schemas: User: { _id: ObjectId, name: String, country: ObjectId // Reference to schema Country } Country: { _id: ObjectId, name: String } My goal is to retrieve all users who are from "VietNam". Could you provi ...

Hide the mdDialog by providing the specific class name of md-dialog

I am encountering a situation where only one material dialog can be open at a time. However, I need to ensure that the dialog is of a particular class name before hiding it. Unfortunately, I couldn't find any solutions online for this issue. $mdD ...

Using a sequence of array methods like filter, map, and reduce in succession instead of relying on a double loop

Having encountered a perplexing issue that I can't seem to comprehend... here is what I am attempting to achieve. Presented with the following array of objects, products = [ { name: 'Sonoma', ingredients: ['artichoke', 's ...

Storing array values in an object using Angular

I am trying to save array values in an object in the format shown below: {"newpublicareas":[{"area_name":"x", "level":0}]} This is my current implementation: getNewTopLevelS(res){ this.newpublic ...

Q.all failing to execute promises within array

Hey all, I'm currently facing an issue while attempting to migrate users - the promises are not being called. User = mongoose.model 'User' User.find({"hisId" : {$exists : true}}).exec (err, doc)-> if err console.error err ...

Prevent the date each month in asp.net

Is there a way to block Sundays for all months and years in a text box with the Text mode set to Date? <asp:TextBox ID="txtfromdate" runat="server" Enabled="True" OnTextChanged="From_TextChanged" TextMode="Date" ></asp:TextBox> ...

NodeJS loop issue with variable scoping in the context of express and mongoose

My Tech Stack: NodeJS, express, mongoose var i; for(i = 0; i < results.length; i++){ console.log("out: "+i); RegionData.findOne({'rid': results[i].region_id}, function (err, product) { if (product) { console.log("i ...

Enhance your data retrieval from XPATH using Javascript

Here is the layout of an HTML template I am working with: <div class="item"> <span class="light">Date</span> <a class="link" href="">2018</a> (4pop) </div> <div class="item"> <span class="light">From</sp ...

Experimenting with event listener on an element using Jasmine

Within my class definition, I have this code: MyClass = function() { var view = { delegateEvents: function () { this.$el.on('click', 'input[type="radio"]', this.toggleServices); }, toggleServices ...

Ajax request not populating controller with data in ASP.NET CORE MVC

`Hello everyone, I'm running into a problem with my colleague's assignment and could really use some assistance. The issue pertains to ASP.NET Core MVC. I have an API Controller for editing student groups. This API Controller receives a GroupView ...

Determine in an efficient way during mouseover if the control key is being pressed with Vue

My initial approach to tracking whether the control key (ctrl) is pressed while hovering over a <section> is as follows: <template> <section v-on:mouseover="controlKeyPressed = $event.ctrl">...</section> </template> Howeve ...

Unable to retrieve the image

When trying to fetch an image, I encountered the following error: Failed to load resource: the server responded with a status of 404 (Not Found) TopBar.jsx import { useContext } from "react"; import { Link } from "react-router-dom"; ...

Do closures truly behave like objects, or are they something else entirely? (It appears not)

Let me clarify right off the bat that I am not inquiring about how closures function, as I already have a grasp on that concept. What I am curious about is what data type should be assigned to closures. Essentially, a closure can be thought of as a record ...

A guide on efficiently inserting multiple rows containing JSON data into a MySQL database simultaneously using node.js

I'm facing an issue with inserting multiple values into columns simultaneously. Let's say I have JSON data consisting of two rows of information, and I want to insert both rows into my table at one go. My attempt looks like this: var data = [&apo ...

What is the best way to include an "average" line in a nvd3.js Stacked Area Chart?

My Stacked Area Chart is up and running smoothly using NVD3.js. You can view it in action on this working jsfiddle link. var volumeData = [{"key":"Hit","values":[[1.3781628E12,12],[1.3782492E12,9],[1.3783356E12,9],[1.378422E12,4],[1.3785084E12,2],[1.37859 ...

Leveraging RouteProvider in Angular

I've encountered an issue while working with route provider. I'm trying to access a different path on my localhost:8080/showThemes.html page using the following method: <a ng-href="#/category/{{themes.theme}}"> <img class="imgCenter" ...

Jade fails to show image in route with parameter

Currently, I am utilizing express 4 and have images saved in the uploads directory. This is a snippet of my code: app.use(express.static(__dirname + '/uploads')); //This part works app.route('/') .get(function (req, res) { ...

Guide to implementing nested asynchronous calls using a foreach loop

I am eager to enhance my skills and gain a better understanding of how to improve this code. While the current code is functioning, I suspect there may be an issue that needs addressing. Here's the concept: 1: Initially, I send the first HTTP request ...