Enforce file selection using AngularJS based on certain conditions

When data is received from the backend in JSON format, it looks like this:

{
  "data":{
    "xyz":[
      {
        "number":"1",
        "short_text":"Sign Contract",
        "long_text":"Enter names after contract signing",
        "is_photo":false
      },
      {
        "number":"2",
        "short_text":"Inform HR",
        "long_text":"HR has its own workflows",
        "is_photo":true
      }
    ]
  }
}

In the HTML code, a form is populated using ng-repeat:

<tr data-ng-repeat="choice in choices track by $index">
    <td>{{choice.number}}</td>
    <td><p>{{choice.short_text}}</p></td>
    <td><input type="textbox" size="50" class="des-textinput" ng-model="choice.desc" required></td>
    <td><input type="checkbox" ng-model="choice.include"></td>
    <td><input type="file" id="abc{{$index}}" class="photo-upload"
               file-model="pic{{$index}}" accept="image/*">
    </td>
</tr>

The goal is to make the input type file required if is_photo is true in the received JSON. If is_photo is false, then it will not be required.

Based on the given JSON, the first input file will not be required because the value of is_photo for the first row is false, while the second one will be required as the value is true.

To achieve this, additional conditional checks need to be implemented in the AngularJS code.

Answer №1

To ensure a field is required in AngularJS, you can utilize the "ng-required" directive.

If you need further information or guidance, refer to this documentation: https://docs.angularjs.org/api/ng/directive/ngRequired

Here are some examples on how to use it:

<input name="myInput" ng-model="myInput" ng-required="myVar == 2">

//If photo is true required will be true else false
<input name="myInput" ng-model="myInput" ng-required="_photo">

<input name="myInput" ng-model="myInput" ng-required="choice.is_photo">

//Or use some function which returns boolean
<input name="myInput" ng-model="myInput" ng-required="isRequired(choice)">

//Demonstration with form and preventing submission if not valid    
<form ng-app="myApp" ng-controller="validateCtrl"
      ng-init="isRequired=true"
      name="myForm" novalidate ng-submit="myForm.$valid && submit()">
        Username: <input type="text" name="user" ng-model="user" 
                         ng-required="isRequired">
        Email : <input type="email" name="email" ng-model="email" required>
        <input type="submit" ng-click="isRequired=!isRequired;" />
</form>

    <script>
       var app = angular.module('myApp', []);
       app.controller('validateCtrl', function($scope) {
           $scope.user = 'John Doe';
           $scope.email = '<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="cca6a3a4a2e2a8a3a98caba1ada5a0e2afa3a1">[email protected]</a>';
           $scope.submit = () => {console.log("s");}
       });
    </script>

Answer №2

when employing this technique

it is automatically configured to be necessary if _photo is set to true

<input name="myInput" ng-model="myInput" ng-required="_photo">

Answer №3

To enforce mandatory file upload, utilize the ng-required attribute. For more information, visit the ng-required documentation

<input type="file" id="abc{{$index}}" class="photo-upload"
       file-model="pic{{$index}}" accept="image/*"
       ng-required="choice.is_photo == true" />

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

Using the onMessage event in React Native WebView does not seem to have any functionality

I'm having trouble with the onMessage listener in React Native's WebView. The website is sending a postMessage (window.postMessage("Post message from web");) but for some reason, the onMessage listener is not working properly. I can't figure ...

Utilizing the Kraken.com API to create a message signature with AngularJS

I'm currently tackling Angular2 and for my first project, I want to tap into the Kraken.com API. (I know, I could have chosen an easier task :) The "Public" calls are working smoothly, but I've hit a snag with the "Private" methods. (Those requi ...

What is the correct method for calculating the sum of one input field and multiple output fields?

I have a single input field and multiple calculated output fields using JavaScript :Click here to view the screenshot of the calculated problem You can see the live preview on this link: . When you visit this link, enter "Base on your annual bill amount: ...

Right-align each item when selecting none

Is there a way to change the style of just one of the elements select or option, without affecting the style of both? I attempted to align the select element to the right, while leaving the option elements aligned to the left. However, this did not work a ...

partial download between servers

I have been attempting to transfer/copy a large file from a remote server to my server in segmented parts or chunks. My initial approach involved utilizing a script I found here: . After making some modifications, I integrated a form into the script and e ...

Node-static is reporting that the localhost page cannot be located

I am currently attempting to serve static files using node-static. My plan is to eventually run this as a Windows service using nssm. I have successfully executed this process in the past, however for some reason it is not working now. Here is the code sn ...

How to Easily Add GitHub NPM Packages to Your SAPUI5 Web IDE

Looking to integrate an NPM package from Github into SAPUI5 using the WebIde Framework. Package Link: https://github.com/commenthol/date-holidays/blob/master/README.md#usage Primary Issue: Need a file with the library for importing and copying into the W ...

Create a left-aligned div that spans the entire width of the screen, adjusting its width based on the screen size and positioning it slightly

I have a parent container with two child elements inside. I want the first child to align to the left side and the second child to align to the right side, but not starting from the exact center point. They should be positioned slightly off-center by -100p ...

The functionality of Quickblox is currently experiencing issues when used with subdomain URLs

I have several URLs for the same domain, but they contain subdomains like the following: admin.projectname.com doctor.projectname.com etc.. The Quickblox API call is not functioning properly with these URLs and is displaying the following error message: ...

AngularJS ui-router in HTML5 mode is a powerful combination that allows

Hey, I'm looking to implement HTML5 mode in my project. Here's how my file structure looks: mypage.de/mysub I can only make changes within the "mysub" directory. So far, I've added the following into my index.html: <base href="/mysub/ ...

Using a conditional statement to wrap a react Route

Currently, I am facing a challenge while working with react router. Initially, I had two distinct components being rendered under the same route - one with a parameter and one without (this was how the routes were distinguished). Now, my goal is to add opt ...

Develop a constructor that can be injected

Delving into the world of AngularJS as a beginner, I am starting to grasp the intricacies and distinctions between factory, service, and controller. From my understanding, a factory serves the purpose of returning a "value object" that can be injected. Mos ...

Searching patterns in Javascript code using regular expressions

I am dealing with two strings that contain image URLs: http://dfdkdlkdkldkldkldl.jpg (it is image src which starts with http and ends with an image) http://fflffllkfl Now I want to replace the "http://" with some text only on those URLs that are images. ...

Modify the layout of the date selector to display weekdays instead - material ui

How can I change the datepicker format to display weekdays (Monday, Tuesday,..) instead of MM/dd/yyyy? Currently, the datepicker is set up with the format format="MM/dd/yyyy". Would it be possible to modify this? Here is the source code: <MuiPickers ...

Laravel Mix fails to recognize VueJs integration in Laravel

Having an issue setting up VueJs with laravel 5.7 and mix where it keeps saying VueJs is not detected. I've already executed the npm install command. Below is my welcome view: <!doctype html> <html lang="{{ str_replace('_', '- ...

Combining Versioning with BundleConfig.cs: A Comprehensive Guide

Encountering a recurring issue where changes made to CSS or Javascript files do not reflect in client browsers unless they manually refresh the page with ctrl+F5. This poses a challenge, especially in a school system with numerous users who may not be awar ...

Wildcard routes for publicly accessible files

I have a collection of "widgets" with both client and server-side .coffee files (client representing Backbone.js model/view and server corresponding to ExpressJS routes), all organized within the main project directory: my-node-expressjs3-project/ src/ ...

Issue: .catch(error) function in Node / Express not returning as expectedDescription: After

I'm currently developing a REST API and focusing on effectively managing all error scenarios. Upon successful completion of the API call, I make sure to return the success object to the calling function and then send the response to the client. Howev ...

Removing a function when changing screen size, specifically for responsive menus

$(document).ready(function () { // retrieve the width of the screen var screenWidth = 0; $(window).resize(function () { screenWidth = $(document).width(); // if the document's width is less than 768 pixels ...

Obtaining numerical values from a string with the help of Selenium IDE

I've gone through numerous solutions for this issue and attempted all of them, but none seem to be effective. Despite its seemingly simple nature, I am struggling with the following task; My objective is to extract a numerical value from a string and ...