Creating a dynamic directive in AngularJS: Learn how to add or remove it from the DOM based on specific conditions

Suppose I have a customized modal directive that looks like this:

return {
  restrict: 'E',
  templateUrl: 'modal.html',
  scope: {
    modalContent: "&",
    modalOpen: "&"
  }
}

And in the HTML:

<ng-modal modal-content="content" modal-open="active"></ng-modal>

How can I ensure that the modal is not present in the DOM when it is closed, and only gets inserted into the DOM when opened? I need to include the directive in the HTML for it to function properly, but this means the modal is already there even if it's not visible.

I have tried creating a Plunker with my progress so far here, but it only toggles the modal using CSS classes instead of completely removing it.

EDIT:

I have made another version available here, which actually adds and removes the directive from the DOM. This approach involves splitting the logic for adding and removing the directive between the directive itself and an external controller (the controller handles adding the element, while the directive handles removal). Is there a way for the directive to handle all of this on its own?

Answer №1

Have you achieved your desired outcome with this solution? I enclosed the content of your template within a single div for ease of accessing the entire chunk as one variable. Subsequently, I included and excluded that div based on whether you wish to display or hide it.

It seems impossible to eliminate the <ng-modal> element completely, but at least everything inside it can be removed...

Check out the demo here

html

<div>
  <div class="modal hide">
    <h4>{{modalContent.title}}</h4>
    <p>{{modalContent.text}}</p>
    <button ng-click="close()">Close Modal</button>
  </div>

  <div class="modal-overlay"></div>
</div>

js

var ModalDirective = function() {
  return {
    restirct: 'E',
    templateUrl: 'modal.html',
    scope: {
      modalContent: "=",
      modalOpen: "="
    },
    link: function(scope, element, attrs) {
      var modalElements = element.children()[0];
      console.log(element);

      function addModal() {
        console.log('Opening modal');
        element.addClass('open');
        //add the modal elements back into the directive
        if (modalElements) {
          //should be 0
          console.log('Element child count before add', element.children().length);
          element[0].appendChild(modalElements);
           //should be 1
           console.log('Element child count after add', element.children().length);
        }
      }

      function removeModal() {
        element.removeClass('open');
        console.log('Closing modal');
        if (modalElements) {
          //remove the modal elements from the directive
           //should be 1
          console.log('Element child count before remove', element.children().length);
          element[0].removeChild(modalElements);
          //should be 0
          console.log('Element child count after remove', element.children().length);
        }
      }

      scope.$watch('modalOpen', function(newVal, oldVal) {

        if (newVal) {
          addModal();
        } else {
          removeModal();
        }

      });

      scope.close = function() {
        scope.modalOpen = false;
      }
    }
  }
}

Answer №2

Using jquery method:

$(element).remove()

Without relying on jquery library:

element.html("")
element.remove();
element.empty();

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

Data merging in Firebase 9 and Vue 3 is not functioning properly

I am facing an issue with merging data in my firebase database. I consulted the documentation at https://firebase.google.com/docs/firestore/manage-data/add-data for guidance. After attempting to merge data using setDoc, I encountered an error (Uncaught Ty ...

Tips for accessing and displaying JSON data using jQuery

Data in JSON format: [ { "ID":"25", "Serial":"1", "Purchase_id":"8", "Item":"23", "Unit":"1", "HSN":"84212120", "Quantity":"10", "Purchase_rate":"100", ...

Guide on utilizing personalized fonts with Handlebars and Puppeteer

I have a Handlebar template that I am converting to PDF using Puppeteer. My question is how can I incorporate custom fonts? Currently, I have a static folder declared in my app.js file like this: app.use(express.static(path.join(__dirname, 'assets&ap ...

What is the best way to trigger an event from a child component to a parent component in

parent.component.ts public test(){ //some code..... } parent.component.html <app-child (eventfire)="test($event)"></app-child> In this scenario, the child component button is displayed within the parent component. However, there i ...

How come executing a function in the Node.js REPL using )( actually functions?

In JavaScript, why is it possible to call a function like this when tested with node.js: ~$ node > function hi() { console.log("Hello, World!"); }; undefined > hi [Function: hi] > hi() Hello, World! undefined > hi)( // Why does this work? Hell ...

Uploading video files using XMLHttpRequest encountered an error on a particular Android device

One of our testers encountered an issue where they failed to upload a video file (.mp4) on a specific Android mobile phone. Interestingly, the same file uploaded successfully on an iPhone and another Android device. To investigate further, I attempted to ...

What is the best way to retrieve a complete DynamoDB scan response using aws-sdk-js-v3 without object types included in the marshaled response?

After struggling with the AWS JS SDK V3 documentation and examples, I decided to share my findings to help others. The official SDK docs were frustrating and misleading, especially when it came to showing marshaled output properly. While the DDB Doc client ...

The Value of Kendo Data

Below is my current kendo code snippet: <script> $("#dropdowntest").kendoDropDownList({ optionLabel: "Select N#", dataTextField: "NNumber", dataValueField: "AircraftID", index: 0, ...

A guide to reordering table rows by drag-and-drop with JavaScript

Seeking assistance with swapping table rows using JQuery UI. Although successful in the swap, struggling to retrieve row numbers during the drag and drop event. Understanding the row number is essential for subsequent tasks. Any help would be greatly appre ...

The icon in Material UI button is missing from the display

The button is functional, but the icon inside it isn't displaying correctly:https://i.sstatic.net/MXhIH.jpg Here is the code for the button: <Button color="secondary" aria-label="add an alarm"> <AlarmIcon></AlarmI ...

What is the best way to reset an HTML file input using JavaScript?

Looking for a way to reset the file input in my form. I've tried setting the sources to the same method, but it doesn't delete the selected file path. Important: Trying to find a solution without having to reload the page, reset the form, or us ...

Angular SPA Routing for .Net Core 2.0

Having recently created a new Angular SPA project using the .Net core 2.0 SPA templates, I find myself facing some challenges as a newcomer to Angular/Typescript and HMR. While most functionalities were working smoothly at first, I noticed a peculiar issu ...

Facing an issue with sending data in AJAX Post request to Django View

I have been trying to send data from the frontend to the backend of my website using AJAX. Below is the post request view in my Django views: def post(self, request): id_ = request.GET.get('teacherID', None) print(id_) args = {} ...

The data binding feature in this Angular web application is malfunctioning

Utilizing a WCF REST service in an AngularJS application, I am attempting to showcase a single record based on the Account Holder's Last Name. The method type is GET. When posting the value to the WCF service and receiving the values, it checks them i ...

Using jQuery to Capture Datepicker Input and Assigning to PHP Variable

I need help figuring out how to save a jQuery datepicker value in a php date formatted variable. My goal is to have: input field named "reviewdate" = 03/02/2015 input field named "reviewmonth" = 3 Both values should be stored in a mysql database. I am ...

Switches in a React-Native ListView are not refreshing properly

Situation: I encountered an issue with a ListView of Switches Problem: The Switches are not changing state when pressed. When debugging, each switch appears to be checked momentarily after the setValue function is called, but then reverts back to unchecked ...

Tips for accessing raw POST data in PHP using $_SERVER

I am facing a challenge with my dynamic page where I use on-page filters that modify the data through AJAX response. My concern is how to access raw POST data when it's not visible in the URL... The link on my page appears as "example.com/default/lis ...

Changing the Direction of News Ticker Movement from Right to Left

I need to switch the news ticker movement direction from right to left to left to right because I will be using Arabic language, so it is crucial to change the movement direction. Despite trying for several days, I have been unable to find a solution. HTM ...

Creating key elements in JavaScript with the push() function

I'm working on a basic shopping cart system using JavaScript (Ionic 2 / Angular). In my PHP code, I have the following: <?php $cart = array( 48131 => array( 'size' => 'STANDARD', 'qty' => ...

Angular2 - Error: The view has been destroyed and cannot be updated: detectChanges

My application keeps encountering this persistent error: extensions::uncaught_exception_handler:8 Error in event handler for runtime.onMessage: Attempt to use a destroyed view: detectChanges at ViewDestroyedException.BaseException [as constructor] (chrome ...