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

Avoid updating the callback in every update by using React's useEffect

Is there a way to avoid continuously updating a callback in useEffect?. For instance, I am subscribed to an event with geofire, which listens for changes and receives locations. I want to update my state without subscribing every time there is an update. ...

Access a webpage in an html document using URL variables

In the process of developing an MVC web app without utilizing any MVC framework, I have created an index.html file with a section that dynamically loads all the views as needed by the user. However, I encountered an issue where direct URLs such as www.foo. ...

Problem arises with chai-http middleware when employing dynamic imports in chai 5.1.1 version

Currently, I am utilizing npm chai version 5.1.1 which has transitioned to supporting only imports and not requires. My use of dynamic imports has been successful so far. However, I have encountered an issue when incorporating the chai-http middleware with ...

Best Practices for Making Remote Requests in Ruby on Rails

Currently, I am creating a Single Page Application using Ruby on Rails for the first time. Although I am still learning, I have set up a side menu with links and a container on the right part of the page to display partial pages. An example of one of my me ...

Challenges with Webpack sourcemaps

As I delve into learning nodejs and react, my current challenge lies in building bundle.js and debugging it within the browser. However, despite creating the bundle.map file, I am faced with errors as the webpack tab fails to appear in the browser. DevTool ...

Show an empty table/data grid with blank rows using Material UI

I am attempting to showcase a table with empty lines and a predefined height, even when there is no data to display initially. By default, the table appears without any visible lines. My goal is to have these empty lines displayed, ensuring that the table ...

Leveraging routes from external modules in AngularJS applications

If I decide to modularize my controller and its view as a bower component, my plan is to set up the route for this module to handle the '/login' URL. var routes = [ { "key": "aes", "value": { "abstract": true, ...

Unable to access the done property in an AJAX JSON promise

Trying to dive into the world of JavaScript promises. My goal is to create a button that triggers a function displaying the result of a promise from another function. So far, I've been following tutorials and here's where I'm at: function my ...

Error: Unable to access the 'clearAsyncValidators' property as it is undefined when running Jest tests on an Angular component

Encountering an Error While Testing Components with Jest Here is my code block for onClickLogin() method: onClickLogin() { if(this.loginForm.valid) { this.api.getLoginData().subscribe(res => { const user = res.find(a => { ...

What is it about Kyle Simpson's OLOO methodology that seems to swim against the tide of Typescript's popularity?

Disclaimer: this post might come across as impulsive. Warning for Typescript beginners! Also, a bit of a vent session. Recently, I delved into the OLOO approach from the YDKJS book series within a Typescript and Node environment. // ideal JS syntax le ...

Retrieve worldwide data for the entire application in Next.js during the first page load

Within my Next.js application, I am implementing search filters that consist of checkboxes. To display these checkboxes, I need to retrieve all possible options from the API. Since these filters are utilized on multiple pages, it is important to fetch the ...

Extracting the value of *data* from my HTML and displaying it in the console with Javascript

I'm struggling to figure out what's going wrong with this code. I've done some research online and it seems like I should just include the window.onload = function() at the beginning of my code. However, no matter what I try, the value alway ...

Tips for updating Nodejs' module dependency to a newer version

Currently, my project utilizes the react-cropper library which includes version cropper ^0.10.0. However, I require certain methods from cropper version 0.11.1. To address this issue, I decided to fork the project to my own GitHub repository in order to up ...

Guide to adding and showing records without the need to refresh the webpage using CodeIgniter

Hey there! I've got a code snippet here for inserting and displaying records without refreshing the web page using AJAX and plain PHP. However, I'm not sure how to set this up using CodeIgniter. Can someone please lend a hand? Here's what I ...

Issue with Tooltipster plugin causing jQuery function not to trigger upon clicking the link within the tooltip

Recently, I've been experimenting with a jquery plugin called Tooltipster by inserting some HTML into the tip with an href link. The problem arises when I try to add a class to the href and fire a jquery function upon clicking it. No matter how much I ...

Transferring a header across a series of interconnected services

I have a script that calls two services, combines their results, and displays them to the user. The services are: Service 1 (hello) and Service 2 (world), resulting in "Hello world". I want to include an ID in the headers to track the route of the calls. ...

There seems to be an issue with the angular login feature using ui-router, as it is not able

Implementing a custom login module for my website as shown below: angular.module('caknow', [ 'ui.router', 'ngStorage', 'authentication', 'login' ]) .config(['$stateProvider', '$url ...

Issue encountered when trying to remove an event while a dialog is closed in a React useEffect

While working with my open dialog, I attempted to include a 'key-down' event. Unfortunately, the event continues to trigger even after the dialog is closed. To address this issue, I encapsulated the event handling function within the useEffect h ...

Saving file with HTML download button results in only HTML document being saved

I am attempting to include a "download file" button on my gatsby website as shown below: <a href="../../images/project-logos/placeholder-company-logo.png" download="test" className="responsive-square project-logo" > <img sr ...

Divide an HTML file into separate documents upon submitting a form

Is there a way to input HTML into a text area, then upon submission, have the system read the file, identify the class selector, and separate the HTML into multiple files saved in a directory? If you have any thoughts on how this could be accomplished, pl ...