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

Combine Immer and NgRx reducer for improved state management

Upon analyzing redux and ngrx, it appears that immer is the preferred library for creating a copy of the state before storing it. In following the example provided by immer, I implemented the following code in my reducer: on(exampleActions.updateExample ...

Error message in Angular js: Unable to load file using XMLHttpRequest

Encountering an error while debugging an Angular JS application in the WebStorm IDE. The error message states: "XMLHttpRequest cannot load file:///C:/Users/../list.html. Cross origin requests are only supported for HTTP." Provided Javascript code : var a ...

"Partially loaded" when document is ready

Is there a way for me to trigger a function once the element identified by #container has finished loading in the DOM? Instead of waiting for the entire DOM to load using document.ready(), I'd like to start populating #container right after it's ...

JavaScript: How to identify and select a specific item from a context menu

Currently diving into the world of JavaScript, so please keep that in mind when explaining. My main goal is to figure out a way to detect when a user triggers a right-click or uses the context menu from the keyboard. Specifically, I want to know if they s ...

Put the code inside a function. I'm new to this

My goal is to encapsulate this code: if($(window).width() > 980) { $(window).on("scroll", function() { if($(window).scrollTop() > 20) { //add black background $(".x-navbar").addClass("active"); $(".x-navbar .desktop ...

Effortless Ways to Automatically Accept SSL Certificates in Chrome

It has been quite some time that I have been attempting to find a way to automatically accept SSL certificates. Unfortunately, I haven't had any success yet. The scenario is this: I am working on selenium tests and every time I run the test on Chrome, ...

Error: An anomaly token was encountered while deploying a Laravel/Vue project using the pipeline yml in Yarn Run

I have encountered a challenge while trying to deploy my project to a server using bitbucket-pipeline with a .yml script. The project consists of a Laravel backend with PHP 7.4 and a Vue Js frontend. The issue arises during the frontend build process with ...

The conditional statement in the given code snippet is failing to execute properly

const checkCondition = (props) => { let conditionMet = false; console.log('-----****----',props); if(props && props.isAllowed) { conditionMet = true; } if(someOtherCondition) { return( <li><Link className=" ...

Tips for managing Ajax JSON response in a PhoneGap application

Although there are a few posts on this topic, I am struggling to piece together the necessary components to make it work. I am in the process of converting a web application into an app using phonegap and I am attempting to create a search form that retri ...

"Encountering a problem with compression in Kafka while using the Node.js client with

I am currently utilizing the kafka-node library to consume data from Kafka. It appears that the data I am receiving is compressed with SNAPPY. How can I decompress this data once it has been retrieved? I attempted to use the node-snappy library for decompr ...

Is it possible to create nested states or views for layout with a leftbar using ui-router?

In my current layout, the Sidebar and Headerbar will always be displayed with context-specific content. I see two possible options for organizing this: nested states (sidenav > Headerbar > Content) or using views. However, I am having trouble understanding ...

When a fresh tile is loaded in Mapbox, an event is triggered

As I work with the Mapbox GL JS API to manipulate maps, I find myself wondering if there is an event that can inform me whenever a new tile HTTP request is made. My code snippet looks like this: map.on("dataloading", e => { if(e.dataType ...

Connect my Vue.js model data to the object that will be used for submission

I need help figuring out how to bind data from my input field into my Vue.js model. I've tried putting the UnitName inside the model but it's not working. Can someone provide some guidance on how to achieve this? new Vue({ el: "#app", da ...

The unique filter in AngularJS ng-repeat ensures that only one result is displayed

I am working with a JSON data structure that contains information about hotels and prices. Each hotel object has an array of prices, each price has an array of rates, and each rate includes a net property. My goal is to display unique net prices from all ...

Angular JS is encountering an issue where the promise object is failing to render correctly

I'm currently learning Angular and I have a question about fetching custom errors from a promise object in Angular JS. I can't seem to display the custom error message on my HTML page. What am I missing? Below is my HTML file - <!DOCTYPE htm ...

Encountering an "Undefined index" error when attempting to send a file and path using FormData through

I have a question about my code. I am trying to send a file and a path to the server. The path needs to be constructed using these variables so that I can use it to output the file later on. var FD = new FormData(); var MyString = "uploads/docs/KEP" + m ...

Is there a way to customize the Webpack output to incorporate specific options solely for a particular bundle?

Currently, I am using Webpack 4 to build multiple bundles. My requirement is to add the output options libraryTarget and library for a single bundle only. The default configuration looks like this: output: { path: path.resolve(__dirname, 'dist/j ...

What are the alternatives to invoking a server-side C# method from JavaScript without using a WebMethod or UpdatePanel?

I am looking for alternatives to using an update panel. The common WebMethod approach is causing errors with the code below: private string currentHtml() { StringWriter str_wrt = new StringWriter(); HtmlTextWriter html_wrt = new Htm ...

Error: Trying to access the 'previous' property of an undefined value

I keep encountering an error with functions in firebase: TypeError: Cannot read property 'previous' of undefined at exports.sendNotifications.functions.database.ref.onWrite (/srv/index.js:5:19) at cloudFunction (/srv/node_modules/firebase-functi ...

Potential issue of excessive memory usage in node.js when running an Express server with PM2

Currently, I am focusing on a specific aspect of a suite of services designed to work in conjunction with an app/platform. The particular area that requires assistance is related to a vanilla express server used to provide our client app (a react app). We ...