Angular Directive: Enabling Form Validation for Submit Button Directive

Managing validations for multiple forms in my project has been quite challenging. Each form requires specific validation expressions, along with a loading element which complicates the reuse of buttons. To tackle this issue, I thought of utilizing a directive instead. However, when passing the expressions through attributes, they do not update or validate as expected when users input data - essentially behaving like static strings rather than dynamic expressions.

My goal is to achieve something similar to this:

<submit-button label="My Label" validate="!myForm.$valid"></submit-button>

This should translate to:

<button ng-disabled="!myForm.$valid">My Label</button>

For reference, here's a basic isolated template on jsfiddle showcasing my progress so far: https://jsfiddle.net/lucasbittar/8m992bet/3/

Any guidance or assistance would be greatly appreciated!

Answer №1

To easily accomplish this in the specified Angular version, you can make use of a two-way attribute binding on your directive. Simply bind the validate attribute or scope property to your expression and then reference it in the ngDisabled directive.

It is important to remember that directives like ngDisabled (and other ng-prefixed ones, if I recall correctly) work directly with expressions, so avoid using double brackets for interpolation.

Your directive code will look something like this:

function submitButton () {
  var submit = {
    restrict: 'E',
    require: ['^form'],
    template: '<button ng-disabled="validate">{{ label }}</button>',
    scope: {
      validate: '='
    },
    link: link
  }
  return submit;

  function link (scope, el, attr, formCtrl) {
    scope.label = attr.label;
  }
}

You can test out the functionality by following this fiddle link: https://jsfiddle.net/8m992bet/6/

Keep in mind that if desired, you could achieve similar results by utilizing an inherited scope in your directive along with scope.$watch, but opting for a two-way binding approach is simpler.

Additionally, note that in Angular 1.5 you have the option to use one-way binding on a directive using < instead of =.

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

Sending an AJAX request will only transmit a portion of an array when using the JSON.stringify

I have a JavaScript array that is constantly updated. Here's how I initially set up the array... columnArray = ["userID", "Date", "trialType", "cue", "target", "response", "accuracy", "lenAcc", "strictAcc", "fkpl", "totalTime"]; var dataArray = []; ...

Hiding the C3 tooltip after engaging with it

I'm currently expanding my knowledge on utilizing C3.js for creating charts, and one aspect I'm focusing on is enhancing the tooltip functionality. Typically, C3 tooltips only appear when you hover over data points as demonstrated in this example ...

Issue with deactivating attribute through class name element retrieval

There are multiple input tags in this scenario: <input type="checkbox" class="check" disabled id="identifier"> as well as: <input type="checkbox" class="check" disabled> The goal is to remov ...

JavaScript: Eliminate a specific element and retrieve the modified array

Is there a way to remove only one instance of an item from an array, even if there are multiple duplicates of that item? For example: let array = ["abc", "def", "ghi", "def"]; const toRemove = "def"; I attempted to find the index and splice the array, but ...

Building a modal in ReactJs

I recently started working with ReactJs and I'm attempting to implement a popup window using the onclick event. Here is the tutorial I am following - https://dev.to/skptricks/create-simple-popup-example-in-react-application-5g7f File - /src/componen ...

JQuery implementation of Axis webservice call

Trying to invoke my Axis webservice with the code below var wsUrl = "http://localhost:8080/TestServ/services/TestCls?wsdl"; var soapreq = "<soapenv:Envelope xmlns:soapenv=\"http://schemas.xmlsoap.org/soap/envelope/\" xmlns:cod=\"http:// ...

http.get is ineffective when utilized within a for loop to retrieve data from mongo through express

I am currently facing an issue with fetching data from MongoDB using Express to Angular within a for loop. Despite being able to access the data inside the GET instance, I'm struggling to do so outside of it. Below is a snippet of my code: var daily_ ...

Using Node.js to import modules that have been webpacked

I'm faced with the challenge of managing a multitude of files that come along when installing various modules using npm install, each with its own dependencies. To simplify this process, I am considering consolidating all required libraries using web ...

What methods can be used to block the input of non-numeric characters in a text field?

I stumbled upon this particular inquiry. Although, the majority of responses involve intercepting key presses, checking the key code, and halting the event if it does not match an acceptable key code. However, there are some issues with this approach. ...

Attempting to transmit information to database using AJAX in the context of CodeIgniter

I'm having some trouble with my AJAX setup. It doesn't seem to be posting any data to the database, despite trying various solutions I found online. That's why I've turned to this platform for help. When testing in Postman and sending ...

When utilised within the same function, JSON values in JavaScript can yield varying results

Recently, I've been grappling with a JavaScript issue that involves fetching JSON values as data-attributes to populate a modal. This task sounds simple enough, but as a newcomer to this field, I find myself facing challenges. The main goal is to ite ...

An error in syntax is being triggered by the Php file being accessed through the <script src="list.php"></script>

We're facing an unusual problem with our online ordering platform script that we purchased a few months ago. It had been functioning perfectly for several months, but now we're encountering an issue! The website page is not loading, and when we c ...

Develop an enhancement for the Date object in Angular 2 using Typescript

Using the built-in Date type, I can easily call date.getDate(), date.getMonth()...etc. However, I am looking for a way to create a custom function like date.myCustomFunctionToGetMonthInString(date) that would return the month in a string format such as &a ...

Ways to check the functionality of an Angular service function that returns an $http request

My service is quite simple as it just makes an $http request angular.module('rootApp') .factory('projectService', ['$http', function ($http) { return { getProject: getProject, getProjects: ...

Launching a personalized Mailchimp form

I am trying to implement a custom mail chimp form that pops up upon page load, similar to what Groupon and Fab do. I have the code for the form copied on our server but I'm struggling to create a pop-up effect when the page loads. I have tested shadow ...

Using the ternary operator to insert elements from one JavaScript array into another array

In my React form, I am dealing with an array of objects that represent different fields. Depending on a boolean state, I need to dynamically change the sequence of fields displayed. While I have no trouble inserting a single object into the array, I am s ...

Conceal descendant of list item and reveal upon clicking

In my responsive side menu, there is a submenu structured like this: .navbar ul li ul I would like the child menus to be hidden and only shown when the parent menu is clicked. Although I attempted to achieve this with the following code, it was unsucces ...

utilizing vuex store within a JavaScript document

Currently, I'm encountering an issue while attempting to access my store from a helper function file: import store from '../store' let auth = store.getters.config.urls.auth An error is being logged: Uncaught TypeError: Cannot read prop ...

Modify the values of several dropdown menus (5 in total) at once using jQuery. The values will be dynamically retrieved from a JSON file

https://i.sstatic.net/9vjlz.png Dropdown values for the first dropdown are 1, 2, 3, 4, 5. Dropdown values for the second dropdown are 25, 26, 27, 28, 29. Dropdown values for the third dropdown are 35, 36, 37, 38, 39. The goal is to have each dropdown load ...

Accessing information from a database table using Highchart and Ruby on Rails (ROR

I have a Ruby on Rails application that utilizes highcharts. I am currently working on enhancing it to display the amount of time spent on specific projects. To demonstrate what I am trying to achieve, I have created a JSFiddle example which can be found h ...