Angular-Formly: Ensuring field requirement based on drop-down selection

I am looking to implement a functionality where an input field becomes required when a specific option is selected from a dropdown box. In my case, the fields are duplicated once an option is chosen to allow users to select multiple options. Specifically, if 'exportSupplier' is chosen, then 'agreementReference' should be marked as required. However, if there are multiple 'exportSuppliers' and at least one of them is not chosen, then the 'agreementReference' fields should not be required.

How can I dynamically set the 'agreementReference' field as required based on whether the corresponding 'exportSupplier' has been selected?

    vm.exportSuppliers = [{ exportSupplier: '', agreementReference: '' }];

    vm.exportSupplierFields = [
        {
            fieldGroup: [
                {
                    className: 'col-xs-6',
                    key: 'exportSupplier',
                    type: 'select2',
                    templateOptions: {
                        label: 'Export Supplier',
                        required: false,
                        options: [],
                        onChange: function() {
                            vm.addExportSupplier();
                        }
                    }
                },
                {
                    className: 'col-xs-5',
                    key: 'agreementReference',
                    type: 'input',
                    templateOptions: {
                        label: 'Agreement Reference',
                        onChange: function() {
                            vm.addExportSupplier();
                        }
                    },
                    expressionProperties: {
                        'templateOptions.required': '!!model["exportSupplier"]'
                    }
                }
            ]
        }
    ];

    vm.addExportSupplier = function() {
        if (vm.exportSuppliers[vm.exportSuppliers.length - 1].exportSupplier || vm.exportSuppliers[vm.exportSuppliers.length - 1].agreementReference) {
            vm.exportSuppliers.push({ exportSupplier: '', agreementReference: '' });
        }
    };

My HTML

<div ng-repeat="supplier in vm.exportSuppliers" class="row">
    <formly-form model="supplier" fields="vm.exportSupplierFields"
        form="vm.informationExportSupplier.form" index="$index">
    </formly-form>
</div>

I have experimented with different ways to incorporate $index into the 'templateOptions.required' field without success.

Answer №1

I have attempted various approaches to incorporate $index into the 'templateOptions.required' field, but I have not been successful.

<div ng-repeat="supplier in vm.exportSuppliers" ng-init="outsideIndex = $index">
    <formly-form model="supplier" fields="vm.exportSupplierFields"
        form="vm.informationExportSupplier.form" index="$index"
        options="{data: {outsideIndex: outsideIndex}}">
    </formly-form>
</div>

According to the documentation:

options

Options for the form.

data

This is an object where you can place any necessary information.

— Angular-formly formly-form Directive API Reference

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

transmit a binary image to a modal using Angular

I am facing an issue with my code where I am unable to pass a binary image to a modal. The image displays correctly as a jpeg in the view, and I need it to display the same way in the modal as well. View <h4 style="color: #3953a5; font-size:22px;"&g ...

How to convert a string of comma-separated values into an unordered list using ng-repeat in AngularJS

In my code snippet, I am utilizing an array named data.list to store mandatory and optional appointments. data.list.push({ mandatory: appt.getDisplayValue('mandatory_appointments'), optional: appt.getDisplayValue('optional_appointments& ...

Methods for obtaining a directive's scope value and utilizing it in another directive within angularjs?

I have a specific requirement to transfer the scope of one directive to another directive and enable two-way binding. The goal is to update JSON values whenever the ng-model changes. In the example below, the JSON contains rowsets with attributes that nee ...

Is there a compatibility issue with AngularJS ng-repeat in Chrome and IE compared to Firefox?

I am fetching some data using the $http.get method $http.get('toDOTasks.json') .success(function (response) { $scope.tasks = response; }); After that, I have: <div ng-repeat="task in tasks| filter:search | orderB ...

Stop fraudulent repetitive ajax calls to PHP

With my website, I've implemented a comment section for blog posts where users can share their thoughts. By clicking a button, an AJAX request is sent to PHP in JSON format. Upon receiving the data, PHP processes and validates it before inserting it i ...

Why isn't my AJAX post in Rails working with a partial JS.slim template?

I'm working on a Rails application similar to a comments board and I want to incorporate ajax functionality. However, my code is not functioning as expected and I can't seem to pinpoint the issue... Here is the code from my controller: # contro ...

Run the js.erb code only when a certain condition is met

I'm feeling a bit lost when it comes to CoffeeScript and JS. I have a quick editing feature that sends an AJAX request and updates the database. Currently, I manually change the edited content's place and display it, but it feels like a workaroun ...

When working in three.js, it's important to remember that geometry.faceVertexUvs[0][0][index] does not equate to geometry.vertices

From what I gather, the uv coords ("texels") of each vertex in a mesh can be accessed using: geometry.faceVertexUvs[ materialIndex ][ faceIndex ][ vertexIndex ] The issue I'm facing is that the vertexIndex seems to have a different mapping order com ...

streamlining form updates in vue

The code snippet provided is functional but unnecessarily complicated and lengthy. I am seeking a more efficient approach to achieve the desired outcome. <h6><label for="number">Change Number</label></h6> ...

Absolute positioned content causing unexpected spacing on top of relative positioned content

I've been experimenting with a fantastic technique by Chris Coyier for implementing full page video backgrounds with content scrolling over the video. However, I've encountered an issue where there's an unexpected gap to the right in Windows ...

Get a hold of a Linkedin profile

When attempting to download most web pages, everything works fine. However, when trying to download a specific LinkedIn page, it seems to output a lot of JavaScript code. from bs4 import BeautifulSoup import requests url = 'https://www.linkedin.com/ ...

Utilizing JavaScript to assign object properties (column names) from an Array of Objects to a specific row and column header

I am currently in the process of implementing a mapping function to display data from an array of objects, initially stored in localStorage, into a table using Material-UI Table. The goal is to map all the specific column names into corresponding Table Ce ...

The alignment is off

<script> var myVar = setInterval(myTimer, 1000); function myTimer() { var d = new Date(); document.getElementById("demo").innerHTML = d.toLocaleTimeString(); } </script> <p text-align="right" id="demo" style="font-family:Comic Sans ...

AngularJS: steer clear of relying on the 'angular' global variable

Is it advisable to refrain from using the 'angular' global object within Controllers, Services, etc? Suppose we want to call the function: angular.isDefined(myVar) How should we reference the 'angular' object? Possible approaches: ...

The src attribute of an HTML element transmits a combined string to the server

My setup includes a ReactJs and Django project. When I send a GET request to my localhost for localhost/index, the server running my Django project returns index.html as expected. However, within the index.html file, there is an html element with src value ...

"Executing the ajax send() function does not result in any changes to the

Just starting to explore ajax and I need some help. Can anyone explain why the address bar is not updating when using ajax send()? The connection is working, but it keeps displaying "There is no variable!" PS: Please note that I prefer not to use JQuery. ...

Validating email addresses in AngularJS with domain verification

Hey there, I'm looking for a way to validate email input on AngularJS. I also want to include a domain check feature. For example, when the input is [email protected], I'd like to show a suggestion to the user indicating that they meant to t ...

Insert a fresh set of data to the top of a highcharts stacked column chart

Is there a way to control the order in which new series are added to a stacked column chart in Highcharts? Currently, using addSeries places the new series at the bottom of the stack. Here's a simplified example of what I'm working on: var chart ...

Mongoose is having trouble identifying the 2dsphere index I created

I am currently attempting to add a 2dSphere index for the field startLocation within the tourSchema. This is how it is defined: startLocation: { type: { type: String, default: 'Point', enum: ['Point'] ...

Utilizing MVC Models to Control Angular Material Checkbox Functionality

I'm getting familiar with the concept of MVC and I've started using MVC5 in combination with angular-material. My goal is to incorporate an MVC model variable with an angular material checkbox (md-checkbox). Below is my code snippet for implemen ...