Update the root scope's parameter within the directive's link function

Encountering an issue while attempting to add a new object to the attachments parameter. Despite successfully pushing the object into the array in the success function of dropzone, it does not reflect in the ng-repeat within template.html.

If you observe closely, the object is pushed into the array but the list doesn't update accordingly.

Any assistance would be greatly appreciated.

directive.js

(function() {
  "use strict";
  module.exports = attachments;

  function attachments($auth) {

    var _token = "Bearer" + " " + $auth.getToken();

    return {
      restrict: 'EA',
      scope: {
          objectType: '@',
          objectId: '=',
          attachments: '='
      },
      transclude: true,
      templateUrl: 'template.html',
      replace: true,
      link: function(scope, element, attrs) {

          element.find(".drop").first().dropzone({
              url: '<url>',
              multiple: true,
              uploadMultiple: false,
              headers: {
                  "Authorization": _token
              },
              init: function(){
                  this.on("success", function (file) {
                      this.removeAllFiles();
                  });
              },
              success: function(file, response){
                  scope.attachments.push(response);
              },
              sending: function(file, xhr, data){
                  data.append("object_id", scope.objectId);
                  data.append("object_type", attrs.objectType);
              }
          });
      }
    }

  }

  attachments.$inject = ['$auth'];

})();

template.html

<div class="cirons-upload">
    <div class="drop"></div>
    <ul class="list" id="preview_list">

    </ul>
    <ul class="list">
        <li ng-repeat="file in attachments">
            <a href="#">{{file.file_name}}</a>
        </li>
    </ul>
</div>

page.html The object invoice has id as integer and attachments as an array.

<cirons-attachments
    object-id="invoice.id"
    object-type="Invoice"
    attachments="invoice.attachments"
></cirons-attachments>

Answer №1

When integrating a third-party library with Angular, some additional steps may be required.

Angular's change detection mechanism may not automatically detect changes made to attachments, as it typically triggers on mouse events or AJAX callbacks. Therefore, you might need to manually initiate a digest cycle.

One common approach is to encapsulate the modification code within a $timeout function.

Here's an implementation example:

(function() {
  "use strict";
  module.exports = customAttachments;

  function customAttachments($auth, $timeout) {

    var _token = "Bearer" + " " + $auth.getToken();

    return {
      restrict: 'EA',
      scope: {
          objectType: '@',
          objectId: '=',
          attachments: '='
      },
      transclude: true,
      templateUrl: 'template.html',
      replace: true,
      link: function(scope, element, attrs) {

          element.find(".drop").first().dropzone({
              url: '<url>',
              multiple: true,
              uploadMultiple: false,
              headers: {
                  "Authorization": _token
              },
              init: function(){
                  this.on("success", function (file) {
                      this.removeAllFiles();
                  });
              },
              success: function(file, response){
                  $timeout(function () { 
                      scope.attachments.push(response);
                  }, 0)
              },
              sending: function(file, xhr, data){
                  data.append("object_id", scope.objectId);
                  data.append("object_type", attrs.objectType);
              }
          });
      }
    }

  }

  customAttachments.$inject = ['$auth', $timeout'];

})();

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

The functionality of the jquery Tab will only be enabled if the script is referenced from the same local page

Attempting to implement jquery UI tab in an MVC4 application. All the necessary scripts and styles have been added in bundleconfig and referenced in layout.cshtml page. Please see the code below: <div id="tabs"> <ul> <li><a ...

Utilizing JavaScript Callbacks in HTML Image Tags

Currently I am working on a small application and looking to include a YouTube section. I have come across a method for obtaining the user's YouTube icon: This is included in the head section of my code: <script type="text/javascript" src="http:/ ...

Having difficulty incorporating TypeScript into Vue

A little while ago, I set up a vue project using vue init webpack . and everything was running smoothly. Recently, I decided to incorporate typescript and ts-loader. I created a file in the src directory with the following content: declare module '* ...

What is the correct method for embedding a javascript variable into a Twig path?

I am looking to include a variable declared in JavaScript into the path for redirecting my page. Here is my code: var id = $(this).attr('data-id'); windows.location = {{ path("mylink", {id: id}) }}; Unfortunately, I am getting an error when ...

Node - What could be causing my gif to run at a slower pace while utilizing GifEncoder?

I am encountering an issue with rendering a Gif using the GifEncoder library (specifically, an older version). The output gif is much slower and appears to lag. Below is the code I have been using: import GIFEncoder from "gif-encoder-2"; import f ...

How can I display a JSON object in HTML using code?

I have implemented the following code snippet: js jQuery.getJSON("https://en.wikipedia.org/w/api.php?action=query&list=embeddedin&eititle=Template:Infobox&eilimit=5&callback=?", { disablelimitreport: true, format: "json" }, fu ...

Easily upload files using Multer without the need for specifying action, method, or encrypt="multipart/form-data" attributes in the form tag

I'm currently facing an issue while trying to upload an image using Multer and Angular's $http.post method. Instead of triggering the form submission with a submit button, I want to directly use $http.post. However, I am encountering a problem wh ...

Having trouble with SCSS in Angular 4 CLI after adding new CSS styles?

After successfully creating a fresh Angular project using the Angular CLI for Angular 4, I decided to generate it with SCSS: ng new myproject --style=sass Everything went smoothly until I attempted to add some CSS code. For instance, when I added the fo ...

Having trouble capturing events in the AngularJS Controller

Currently, I am in the process of setting up a user authentication system. In my research, I came across the 401 HTTP status code and the HTTP Auth Interceptor Module. After downloading the module using bower and adding it to my app module, I realized tha ...

Utilize information from a JSON Array to populate a JavaScript Array

Is there a way to link the data from the $data variable in ajax.php to the this.products[] array in store.js? Both files are separate, so how can I achieve this? The webpage displays the database data returned by ajax.php as shown below: [{"0":"100001"," ...

How to effectively refine a group query in Firestore to obtain specific results

My database structure is set up like this (simplified version): Collection: item_A -> Document: params = {someParameter: "value"} -> Document: user_01 -> Sub-collection: orders_item_A -> Document: order_AA ...

Troubleshooting issue: Failure in proper functionality of Jquery's slideDown

My form is divided into 3 sections, with the latter two initially hidden using CSS. When users click the next button in the first section, the second section is supposed to slide down into view. However, I'm experiencing an issue where the animation s ...

MUI: Transforming the uncontrolled value state of Select into a controlled one with a new component

I'm attempting to develop an edit form for modifying data fetched from a database based on its ID. Here is what I have tried: import React, {FormEvent, useEffect, useState} from "react"; import TextField from "@material-ui/core/ ...

"Enhancing user experience with advanced checkbox filtering in Django using JavaScript

For filtering my results on an HTML page, I am attempting to use checkboxes. I pass my data in a list through a Django view, and then iterate through it using a loop like this: </div> {% for r in rows %} <div class="res_show"> ...

Updating to the latest version of Next.js will result in a modification of the API path

I recently updated my app to the latest version of nextjs (13.1.6) and encountered a problem where all my requests are now failing. It seems that the URL I specified in the request creator, based on the ENV value, is being overwritten. .env file CONST NEXT ...

Executing JavaScript function from external SVG file globally

I am working on an HTML page that includes an external JavaScript module <script type="text/javascript" src="js/js.js"></script> and also an external SVG map called "img/map.svg". My goal is to create clickable objects on the map that will t ...

Assigning a value to a variable outside of a function in AngularJS using $on: Is it possible?

Before calling $on, I need to assign the value of $scope.attestorObj.riskAssessmentRoleAsgnKey to a global variable called roleAsgnKy. I am new to angularJS and would appreciate any help on how to achieve this. This is what I have tried so far... In main ...

Struggling with inputting text in an AngularJS application

I am facing an issue with populating a text input with the output of a function in my HTML code. Despite trying different approaches, I am unable to figure out why it is not working correctly. Below is the snippet of my HTML code: <input type="text ...

Verify if the nested JSON object includes a specific key

Currently, I am grappling with a dilemma on how to determine if within a deeply nested JSON object, featuring numerous unknown arrays and properties, lies a specific property that goes by the name "isInvalid". My objective is to identify this property and, ...

What is the function of async in Next.js when triggered by an onClick

Need help with calling an async function pushData() from a button onClick event async function pushData() { alert("wee"); console.log("pushing data"); try { await query(` //SQL CODE `); console.log("Done&quo ...