Conflicting directives are canceling each other out

I am facing an issue with my two directives. One directive is responsible for checking the file size, while the other ensures that the uploaded file format is valid. When both directives are assigned to an input=file element separately, they work fine. However, when used together, the validFileSize directive seems to interfere with the selectNgValidationFiles directive.

//view

<input type="file" name="uploadedDocs" id="uploadedDocs" data-ng-model="fileStore.file" select-ng-validation-files valid-file-size multiple>

//controller

function validFileSize($parse){

    return {
        require: 'ngModel',
        restrict: 'A',
        link: function(scope, el, attrs, ngModel) {

            var model = $parse(attrs.ngModel);
            var modelSetter = model.assign;
            var maxSize = 2000; //2000 B
            el.bind('change', function() {

                scope.$apply(function() {
                    scope.fileStore.maxSizeError = false;
                    if (el[0].files.length > 1) {
                        modelSetter(scope, el[0].files);
                    } else {
                        modelSetter(scope, el[0].files[0]);
                    }

                    if(el[0].files.length > 0) {
                        var fileSize = el[0].files[0].size;
                        if (fileSize === 0) {
                           scope.fileStore.maxSizeError = true;
                        }
                    }
                    
                });
            });
        }

    }
}

function selectNgValidationFiles() { //if files to be uploaded vary in future, add condition to check type or create new directive
    return {
        require: "ngModel",
        link: function postLink(scope,elem,attrs,ngModel) {
            var validFormats = ['pdf', 'PDF', 'doc', 'DOC', 'docx', 'DOCX', 'jpg', 'JPG', 'jpeg', 'JPEG','png', 'PNG', 'gif', 'GIF', 'pptx', 'PPTX', 'csv', 'CSV', 'xlsx', 'XLSX', 'zip', 'ZIP'];
            elem.bind('change', function () {
                validFile(false);
                scope.$apply(function () {
                    ngModel.$render();
                });
            });
            ngModel.$render = function () {
                console.log('elem : ',elem)
                ngModel.$setViewValue(elem[0].files[0]);
            };
            function validFile(bool) {
                ngModel.$setValidity('pdfIncorrect', bool);
            }
            ngModel.$parsers.push(function(value) {
                var ext = value.name.substr(value.name.lastIndexOf('.')+1);
                if(ext=='') return;
                if(validFormats.indexOf(ext) == -1){
                    console.log('not valid format')
                    return value;
                }
                validFile(true);
                return value;
            });
        }
    }
};

query

What could be causing conflict between my directives? It seems like one directive might be overriding the other, but I'm unsure how to resolve this issue.

Answer №1

Why not consolidate them into a single directive or service function? Validate the file format first, then move on to checking the file size.

The issue may arise from invoking the $scope apply function twice (once in each directive), which usually causes conflicts.

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

There seems to be an issue with a potentially null object in an Angular project while trying to view a PDF file

IDENTIFY THE ERROR: printContents = document.getElementById('print').innerHTML.toString(); ON LINE 4: print(): void { let printContents!: string; let popupWin!: any; printContents = document.getElementById('print').innerHTM ...

Is there a way for me to expand the dropdown menu?

My current dropdown looks like this. I'd like the dropdown menu to span across the screen, something like this: To create my dropdown, I am using https://github.com/angular-ui/ui-select2. AngularJS JQuery Select2 I'm not sure if there is an ...

Guide on sending a request to an API and displaying the retrieved information within the same Express application

I recently developed a basic express app with API and JWT authentication. I am now attempting to enhance the app by incorporating page rendering through my existing /api/.. routes. However, I am facing challenges in this process. app.use('/', en ...

Error message encountered: "Uncaught (in promise) SyntaxError: Unexpected token < in JSON at position 0, specifically occurring on the get request

Upon completing the construction of my project, I have encountered an error following the building of my application. The error message reads: Uncaught (in promise) SyntaxError: Unexpected token < in JSON at position 0 This error only appears on pages ...

Images that were just added to vite4 and vue3 are not appearing after the build on the production environment

I am facing issues displaying newly uploaded images in my Vue 3 project with Vite 4 on production after building. Despite trying various code snippets from the internet, I have not been successful so far. Specifically, I am attempting to display a user&apo ...

AngularJS: Issue with watching arrays and deep $watch functionality

I'm having trouble using the $watch function in AngularJS with an array of boolean values. I want to display a message when there's a change in the array, but it's not working as expected. Check out this code example where the array values ...

Is it possible for me to search within a retrieved document using Mongoose?

My schema is structured as follows... var TerritorySchema = new Schema({ user: Schema.Types.ObjectId, streets: [streets_schema] )}; var StreetsSchema = new Schema({ name: String, odd: [block_schema], even: [block_schema], tags: [S ...

Link that is clickable within the tooltip of a Highcharts graph

My tooltips contain a list of data, and I want each data point to be a clickable link that redirects to the page for that specific data. The issue arises with Highcharts tooltip because it changes based on the x-axis, resulting in the tooltip content chang ...

Is it possible for a destructed assignment to yield multiple objects?

I am faced with a collection of Storybook stories and a function that produces a ComponentStory object. I am aiming to find a concise method for duplicating multiple stories without resorting to repetitive code like this: export const Default = bindStory(T ...

Navigate within a JSON object using an identifier to extract a particular value associated with that identifier

Exploring a JSON object containing nested arrays and objects. The label value acts as the identifier to find and return its corresponding level's metrics value. If the label is located at the second level, retrieve and return the metrics from that lev ...

Using the code `$("img").one('load'` can trigger only a single load event without repetition

I have implemented the following function: function CheckImage(url, index) { $("<img/>").one('load', function () { $("div.photos").append(this); }).attr('src', url).attr('data-photo', '0' + ind ...

Increase the value of X within the given string

I am working on developing an application that transforms the initial string: 1.2.3.X Into multiple strings: 1.2.3.0 1.2.3.1 1.2.3.2 1.2.3.3 1.2.3.4 ...... This is a snippet of the code I have written so far: String.prototype.count=function(c ...

One of the functionalities is not functioning properly: either the validation or the AJAX

My validation code was working fine until I added some ajax code. Now, when I include the onclick="return chk()" in the submit input field, the validation code stops working. But if I remove it, the ajax code doesn't work. How can I resolve this issue ...

Creating sitemaps for multi domain websites using NextJS

We are implementing a next-sitemap package to generate sitemaps for our Next.js pages located in the /pages directory. For pages that come from the CMS, we use server-sitemap.xml with SSR. Despite having 6 different domains, we manage them within a single ...

I am struggling to make my button hover effects to function properly despite trying out numerous suggestions to fix it

As a newcomer, this is my first real assignment. I've managed to tackle other challenges successfully, but this one seems a bit more complex and I'm struggling to pinpoint where I'm going wrong. Despite googling various solutions, none of th ...

One-Time Age Verification Popup Requirement

Hi there! I'm facing a challenge with an age verification pop up on my webpage. Currently, the pop up appears on every page a user lands on, but I only want it to show on their first visit. I've tried using cookies to achieve this but haven' ...

What is the best way to align HTML inputs within a grid, whether it be done automatically or manually using JavaScript?

Arrange 20 HTML inputs with various data types into grid-columns as the user inputs data. Ensure that the grid container has div elements correctly positioned for output. ...

Utilizing angularJS to manipulate select options through objects

I am looking to populate a dropdown with category values using select options from the following object: [{ "_id": "57b4508923a10cd83c79a301", "created_by": "1", "category": "Criminal law", "__v": 0, "delete_status": "0", "active_s ...

Ensure the appropriate TypeScript types are utilized for error middleware in Express

Struggling to properly define the types in my express application. I am encountering issues with my middleware error function and cannot seem to find a suitable example or get the correct types set up. Despite numerous attempts, here is my current version: ...

Navigating within a nested view using Angular's UI-Router

I've encountered a puzzling issue that I've been grappling with for the past three days. It seems like a straightforward problem, but for some reason, it's causing me a lot of trouble. The main parent view in my code contains two child view ...