Discovering existing files on the server using Dropzone in Angularjs

This particular directive is utilized for displaying Dropzone.js on a webpage:

angular.module('dropzone', []).directive('dropzone', function () {
  return function (scope, element, attrs) {
    var config, dropzone;

    config = scope[attrs.dropzone];

    // Creating a Dropzone for the specified element with provided options
    dropzone = new Dropzone(element[0], config.options);

    // Attaching the defined event handlers
    angular.forEach(config.eventHandlers, function (handler, event) {
      dropzone.on(event, handler);
    });
  };
});

In the controller, this code snippet is used:

angular.module('app', ['dropzone']);

angular.module('app').controller('SomeCtrl', function ($scope) {
  $scope.dropzoneConfig = {
    'options': { // Parameters passed to the Dropzone constructor
      'url': 'upload.php'
    },
    'eventHandlers': {
      'sending': function (file, xhr, formData) {
      },
      'success': function (file, response) {
      }
    }
  };
});

For displaying files that are already stored on the server in Dropzone, utilize mockFile and this.emit. How can you access this and execute the emit function?

Answer №1

Here is the solution I used to solve the problem:

'use strict';

angular.module('dropzone', []).directive('dropzone', function ($timeout) {
    return {
        restrict:'AE',
        require: 'ngModel',
        link:function (scope, element, attrs, ngModel) {
            var init = function () {
                var config, dropzone;

                config = scope[attrs.dropzone];

                // create a Dropzone for the element with the given options
                dropzone = new Dropzone(element[0], config.options);


                // Display existing files on server
                if(ngModel.$viewValue !=='' && ngModel.$viewValue !==undefined){
                    var mockFile = {name: ngModel.$viewValue, size: 1234};
                    dropzone.emit("addedfile", mockFile);
                    dropzone.createThumbnailFromUrl(mockFile, "uploads/" + ngModel.$viewValue);
                    dropzone.emit("complete", mockFile);
                }

                // Form submit rest dropzone event handler
                scope.$on('dropzone.removeallfile', function() {
                    dropzone.removeAllFiles();
                });


                // bind the given event handlers
                angular.forEach(config.eventHandlers, function (handler, event) {
                    dropzone.on(event, handler);
                });
            };
            $timeout(init, 0);
        }
    }
});

In the controller:

$scope.dropzoneConfig = {
        options: { 
            url: '/api/uploadimage',
            paramName: "file",
            maxFilesize: .5,
            acceptedFiles: 'image/jpeg,image/png,image/gif',
            maxFiles: 1,
        },
        'eventHandlers': {
            'removedfile': function (file,response) {
                $http({
                    method : "POST",
                    url : "/api/uploadimage/"+$scope.customer.avatar_url
                }).then(function mySucces(response) {
                    $scope.deleteMessage = response.data;
                    $scope.customer.avatar_url='';
                });
            },
            'success': function (file, response) {
                $scope.customer.avatar_url = response.filename;
            }
        }
    };

Include this in your HTML:

<div ng-if="customer.avatar_url!==undefined" ng-model="customer.avatar_url" dropzone="dropzoneConfig" class="dropzone"></div>

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

Is the Scope Staying Static in AngularJS 1.4 when Input Text Changes and Two-Way Binding is Enabled?

Encountering a strange issue with AngularJS 1.4 (TypeScript). The problem lies within the controller where a variable is set and displayed in an input text box. Oddly, when attempting to edit the value in this text box and clicking on a button, the variabl ...

Creating personalized AngularJS directives with two-way binding in a hierarchical structure

I'm in the process of creating a CRUD form using two custom directives. The main directive (crudForm) is responsible for holding all the controls within the form (such as textboxes, textareas, checkboxes, etc.), while the second directive inside it co ...

Setting up external routes in Express: A step-by-step guide

For my Express application, I successfully set up the index route. Now, I'm facing an issue with adding a new route named cart for the shopping cart page. Whenever I try to access the cart route, I encounter a 404 error, which is odd considering it&ap ...

Determine the starting position of a div's CSS bottom using jQuery before the hover animation begins

Currently, I am in search of the CSS value 'bottom' for each div that belongs to the 'shelf-info-text' class. These particular divs can be found inside a parent div called 'shelf-item'. The bottom value is determined automati ...

The definition of the Three.js object is failing to properly define itself

I am currently working my way through a series of tutorials and have encountered an error that I'm struggling to resolve... It's possible that this issue is simply due to my reliance on IDEs with red underlines for syntax errors, but I really ne ...

Is it possible for jquery to reposition and resize div elements?

I need help with a web page layout that consists of a header, footer, and middle area divided into 3 equal columns, each occupying 33% width. My goal is to create an interactive feature where clicking on one column causes it to expand above the other two, ...

Resize a div within another div using overflow scroll and centering techniques

Currently, I am working on implementing a small feature but am facing difficulties with the scroll functionality. My goal is to zoom in on a specific div by scaling it using CSS: transform: scale(X,Y) The issue I am encountering lies in determining the c ...

JavaScript salary calculation function not functioning properly

Once the user inputs the employee's name and the number of hours they worked on the HTML form, the submit button captures this information and stores it in variables for calculating their pay. The script also factors in overtime pay. Despite feeling l ...

Deactivate various choices in a dropdown menu within an angularjs framework depending on the value selected in a separate

I need help with implementing a functionality in my table where each row consists of a dropdown and 2 input boxes. The user should be able to add and remove multiple rows, but the selected state in one row should not be selectable in any other row. For exa ...

Tips for developing an npm package that includes a demonstration application

When creating packages, I believe it's important to include a demo app. However, I'm unsure about the best way to organize the file structure for this purpose. My goal is to have one Github repository containing both my published NPM module and ...

Each time I attempt to read a single document, Next.js and Firebase consistently encounter serialization errors

Currently, I am in the process of developing a blog website, and most of it is completed except for the functionality of being able to click on a post stub to read the full post. Whenever I try to navigate to the post page, I encounter the following error: ...

What are the most effective techniques for utilizing JavaScript modules in both the Server and Browser environments?

Currently, I am in the process of developing a JavaScript project that utilizes NodeJS. There are certain objects that need to be shared between the client and server side. I attempted to employ the module system in Node, but struggled to find an appropria ...

The error message "Exceeded the maximum call stack size in Javascript"

My current project involves using socket.io for sending and receiving data from a server. I have implemented a "Create Game" button on the client side that triggers the creation of a new GameServer on the server side. Following that, I am displaying the ga ...

Using external URLs with added tracking parameters in Ionic 2

I am looking to create a unique http link to an external URL, extracted from my JSON data, within the detail pages of my app. Currently, I have the inappbrowser plugin installed that functions with a static URL directing to apple.com. However, I would lik ...

Tips for invoking a function that yields an object using ng-repeat

I have been attempting to implement nested ng-repeat functionality in my project. The issue I am facing is that the values from the outer ng-repeat need to be passed as a parameter for the inner ng-repeat. I have tried creating a function that returns an a ...

Are there other options available for generating template code aside from using a directive?

After noticing that I had duplicate HTML on multiple screens, I decided to streamline the process by creating a directive. Here is an example of how I created the directive: app.directive('adminRetrieveButton', ['stateService', functio ...

Find a solution to the issue of displaying react icons within JavaScript with embedded objects

When icons are added inside the JavaScript condition, the icon only appears as an object and does not display properly {!signUp ? `${(<FcGoogle />)}` + "Sign in With Google": `${(<FcGoogle />)} Sign Up With Google`} view image descri ...

Any number of elements in a single JSX code snippet

In my React code, I've created a function called optionTemplate to be used as a prop in a React component. const optionTemplate = (option) => { return ( <div className="flex align-items-center gap-2" style={ ...

Guide on eliminating commas by utilizing the replace function in Angular

Check out the code snippet here: https://stackblitz.com/edit/angular-w5ecbw?file=src/app/app.component.ts item.component.ts ngOnInit() { const data = ['.23.2 ms','.23.001 ms', '.23.81 ms', '192,101.02 ms', &apo ...

Issue with MongoDB find() function not retrieving any results (Assignment)

I am currently working on an assignment that requires the use of noSQL databases. Although I understand most of the queries we have to perform in mongoDb, every query I execute seems to return a blank result. Initially, we are required to create a collect ...