AngularJS directive error: Incorrect function invoked

I have two similar scenarios where I need to apply validators for specific files, even though I am aware that this goes against the DRY principle. However, being new to AngularJS, I am still learning the ropes.

module.js

var $moduleExample = angular.module("$moduleExample", ["ngMaterial"]);

$moduleExample.controller("testController", [
    "$scope",
    function (
        $scope,
    ) {
        $scope.fileDialog = function () {
            var el = angular.element("#file-dialog");
            el.trigger('click');
        };
    }
]);

$moduleExample.directive("validJson", function jsonValidFile() {
    var validFormats = ['json'];
    return {
        require: 'ngModel',
        link: function (scope, elem, attrs, ctrl) {
            elem.on('change', function () {
                var value = elem.val(),
                    ext = value.substring(value.lastIndexOf('.') + 1).toLowerCase();
                scope.isModelValid = validFormats.indexOf(ext) !== -1;
            });
        }
    };
});
$moduleExample.directive("validImage", function imageValidFile() {
    var validFormats = ['jpg'];
    return {
        require: 'ngModel',
        link: function (scope, elem, attrs, ctrl) {
            elem.on('change', function () {
                var value = elem.val(),
                    imageValue = attrs.validImage,
                    ext = value.substring(value.lastIndexOf('.') + 1).toLowerCase();
                scope.isImageValid = validFormats.indexOf(ext) !== -1;
            });
        }
    };
});

template.html

<div>
    <md-button ng-click="fileDialog();">
        <md-icon md-font-set="material-icons">file_upload</md-icon>
        upload json
    </md-button>
    <input id="file-dialog" type="file" class="ng-hide" valid-image on-file-change="handleImageFile" ng-model="image" />
</div>
<div>
    <md-button ng-click="fileDialog();">
        <md-icon md-font-set="material-icons">file_upload</md-icon>
        upload image
    </md-button>
    <input id="file-dialog" type="file" class="ng-hide" valid-json on-file-change="handleJsonFile" ng-model="model" />
</div>

The issue arises when the second button is clicked to validate the proper json format, but instead of applying the valid-json directive, it triggers the valid-image directive and validates against jpg.

Both handleImageFile and handleJsonFile functions are only focused on reading the files.

What could be causing this discrepancy?

Answer №1

Within the fileDialog function, I made reference to the file-dialog element. This caused confusion as both directives had identical identifiers and functions.

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

Error encountered while attempting to download PDF file (blob) using JavaScript

Recently, I have been utilizing a method to download PDF files from the server using Laravel 8 (API Sanctum) and Vue 3. In my Vue component, I have implemented a function that allows for file downloads. const onDownloadDocument = (id) => { ...

How can I send back multiple error messages from a pug template in a node.js application with Express?

I am currently working on validating inputs from a form on a Node.js web server using Pug.js and Express.js. The issue I am facing is that when there are multiple problems with the user's input, only the first error is displayed to the user. How can I ...

Ways to insert script tag in a React/JSX document?

private get mouseGestureSettingView() { const {selectedMenu} = this.state; return ( selectedMenu == 2 ? <script src="../../assets/js/extensions/mouse-gesture/options.js"></script> <div className={styles.settingForm}& ...

Issue in Jasmine test: 'Spy should have been invoked'

I've encountered an issue while writing a Jasmine test case for the following Angular function. The test case failed with the message "Expected spy [object Object] to have been called". $scope.displayTagModelPopup = function() { var dial ...

Obtain a masterpiece by creating a canvas in React

Greetings! I have developed a drawing app using react and I am looking for a way to capture what the user has drawn on the canvas when they release the mouse button. This process should repeat continuously until the user stops drawing. Can anyone suggest h ...

What is the best way to create a continuous typewriter effect in Next.js?

I have a unique project that features a typewriter effect, but I'm encountering an issue where it only types the text once. What I really want is for the typewriter effect to continuously loop, starting over and typing out the words again. I've b ...

The JavaScript-generated form element will not be included in the data submitted through the POST method

While it may appear that this question has been asked before, my specific inquiry seems to be unique as I have not found a similar answer in other threads. Therefore, I am initiating a new discussion. My issue revolves around a form which contains a link ...

Unable to logout with ExpressJS passport-local

After pasting the passport-local app into my own, I noticed something interesting: I managed to successfully log in users, but for some reason, I can't seem to get them logged out. app.get('/logout', function(req, res){ req.logout(); r ...

Implementing Vuejs Array Push in Separate Components

I am attempting to extract data from an object and store it in an array using Vue. My goal is to have each value stored in a separate array every time I click on an item. Each click should push the todo into a different array. How can I achieve this separa ...

Discovering pairs of numbers that are not next to each other in an array that has not been

When working with an array of unsorted numbers, the goal is to identify and extract pairs of elements that are not consecutive. Input [2,3,4,5,9,8,10,13] Desired output (2,5)(8,10)(13,13) To achieve this: Input = [2,3,4,5,9,8,10,13] If we arrange the num ...

Tips for utilizing the "get" method in React to submit a form

Is there a way to submit a form using the "get" method to an external URL in react? Similar to how it is done in HTML like in this example: https://www.example.com/form But instead, to a third party URL...? Can I achieve something like this? The goal is ...

Obtaining the data object from a tag in Internet Explorer 8

When using Chrome, the following line of code provides a useful result: $('[data-buyername]').data() It will retrieve the value associated with the tag data-buyername='somethingArbitrary' However, in IE8, the .data() function does no ...

Issue encountered while utilizing combineReducers: "Error: The assetsReducer returned an undefined value during initialization."

Issue: The "assetsReducer" has returned an undefined value during initialization. When the state passed to the reducer is undefined, it must explicitly return the initial state, which cannot be undefined. If no value is set for this reducer, consider using ...

Having trouble generating an image with JavaScript

I am currently working on incorporating an image onto a webpage using JavaScript. Surprisingly, even the alert('This function works!') is not displaying anything! What could be causing this issue? Please assist! <!DOCTYPE html> <html> ...

Retrieve information from a sensor within an Express server and display it on the user interface

Looking for suggestions on resolving a challenge: I have a Node.js module that retrieves data from a sensor, and I am interested in incorporating a UI element to showcase the sensor data (either in real-time or pseudo-realtime). Is there a way to establ ...

Passing data between child components using Vuejs 3.2 for seamless communication within the application

In my chess application, I have a total of 3 components: 1 parent component and 2 child components. The first child component, called Board, is responsible for updating the move and FEN (chess notation). const emit = defineEmits(['fen', 'm ...

The error message "Element is not defined (Object.<anonymous>)" is occurring in the context of Intro.js-react, React, Next.js, and Tailwind

Here is a code snippet: import { useState } from 'react'; import { Steps } from 'intro.js-react'; export default function Dashboard() { const [stepEnabled, setStepEnabled] = useState(true); const steps = [ { intro: &apos ...

Obtaining JavaScript data using Python Selenium Web Driver

I have been attempting to execute a javascript file within a Python script using Selenium WebDriver in order to retrieve the return value from the function. Despite my efforts and research, I have not been successful after spending several hours on this ta ...

Strategies for breaking apart a large, monolithic Node.js JavaScript application

My node.js server application is expanding, and I am looking to split it into multiple files. Below is a snippet of the current monolithic server.js file: var express = require('express'); var app = express(); // other initialization code etc / ...

Use Node.js to transform every spreadsheet into Json format

I have been attempting to convert an Excel file into JSON format. I tried utilizing the "xls-to-json" npm package with the following code: node_xj = require("xls-to-json"); node_xj({ input: "Auto.xlsx", // input xls output: "output.json", // output ...