Creating transclusion templates in a compiled format

<div overlay config="overlayConfig">
    <div class="dismiss-buttons">
        <button class="btn btn-default" ng-click="subscriptions()">Save</button>
    </div>
</div>

app.directive("Overlay", ["$timeout", "$compile", function($timeout, $compile) {
    return {
        restrict: "A",
        transclude: true,
        scope: {
            config: "="
        },
        template: "<div class='overlay'><div ng-transclude></div></div>",
        link: function(scope, iElement, iAttrs, ctrl, transclude) {
            iElement = iElement.find(".ehn-overlay");
            $(document.body).append(iElement);


            scope.$watchCollection("config", function(value) {
                if (scope.config.isVisible === false) {
                    iElement.remove();
                } else {
                    $(document.body).append(iElement);
                }

            });

        }

    };
}]);

Is there a way to resolve the issue of ng-click not triggering after appending the overlay to the body multiple times? I suspect that the element may not be getting compiled properly. Any suggestions to fix this problem?

Answer №1

I attempted to replicate the issue you are experiencing, but I was unsuccessful. You can view a working example on Plunker.

var app = angular.module('plunker', []);

app.controller('MainCtrl', function($scope, $timeout) {
  $scope.name = 'World';

  $scope.config = {
    isVisible: false
  };

  $scope.do = function() {
    $scope.config.isVisible = true;
    $timeout(function() { 
      $scope.config.isVisible = false;
    }, 2000);
  };
});

app.directive("overlay", ["$timeout", "$compile", function($timeout, $compile) {
    return {
        restrict: "A",
        transclude: true,
        scope: {
            config: "="
        },
        template: "<div><div ng-transclude></div></div>",
        link: function(scope, iElement, iAttrs, ctrl, transclude) {
            iElement = iElement.find(".overlay");
            $(document.body).append(iElement);

            scope.$watchCollection("config", function(value) {
                if (scope.config.isVisible === false) {
                    iElement.remove();
                } else {
                    $(document.body).append(iElement);
                }

            });

        }

    };
}]);

View:

<div overlay config="config">
      <div class="overlay"></div>
      <div class="dismiss-buttons">
        <button class="btn btn-default" ng-click="do()">Save</button>
      </div>
    </div>

Some notes to consider:

  1. Avoid mixing jQuery with AngularJs to prevent issues with testability and other potential problems.
  2. There are various overlays specifically designed for AngularJs, so using one of them is recommended unless you are exploring AngularJs concepts.

For a different overlay example that follows Angular conventions, you can check out this Plunker demo.

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

Vuejs fails to properly transmit data

When I change the image in an image field, the new image data appears correctly before sending it to the back-end. However, after sending the data, the values are empty! Code Commented save_changes() { /* eslint-disable */ if (!this.validateForm) ...

The accumulation of classes occurs during the cloning process of a template used for a data array

Encountered an issue while duplicating a template div to generate elements for a dataset. The problem arises from classes stacking up when creating elements for each data entry. Sample JavaScript code: $(document).ready(function(){ var data = [ { ...

Using Javascript to dynamically add and remove elements on click

Whenever I click on a link, I am able to generate input, label, and text. However, I want to be able to delete these elements with the next click event on the same link: I've tried updating my code like this: var addAnswer = (function() { var la ...

Exploring the power of Node.js and EJS through the art of

Recently delving into the world of node.js, I encountered a puzzling issue with my EJS template. It seems that my for loop is not executing properly within the EJS template while attempting to create a basic todo app. Below is the structure of the project ...

Changing variables within anonymous functions in javascript can be done by using the parameters passed into

Hello everyone, I'm currently working on a new JavaScript project and I've encountered an issue. I need to figure out how to change variables in anonymous functions. Can anyone help me with this? updateName : function(){ var firstNa ...

Execute the "organizeImports" trigger through the terminal in TypeScript

One feature of VSCode is its editor capability to organize and clean imports in javascript and typescript files upon saving ( "source.organizeImports": true ). Inquiry Is there a way to trigger this action on a file using the command line? Something alo ...

Best practice for updating Form.Control text using a custom onChange method

Today, I observed a unique behavior while utilizing a custom onChange in a Form.Control. The text in the field no longer updates when a file is selected. I thoroughly checked the Git documentation HERE, but unfortunately, it does not provide information on ...

The ESLint rule "eqeqeq" configuration is deemed incorrect

After successfully running eslint with the provided .eslintrc file, I encountered an issue when making a simple change to use 'standard' instead of 'airbnb-base' as the extend: module.exports = { root: true, parser: 'babel-esl ...

Horizontal scrolling alone is proving to be ineffective

My current HTML code includes a table that is integrated with PHP Laravel. The data is being pulled from Admin.php to populate the table, resulting in it being wider than the screen window. To address this, I added a horizontal scroll bar for navigation pu ...

Guide on sending AJAX requests from Javascript/React to Python REST API and receiving data

In my project, I have developed the front end code using React. There is a simple form where users can input their name, title, department, and other basic string fields. Upon hitting submit, JavaScript triggers an AJAX request to my REST API which is impl ...

The administrator user assigns a user value in the authentication context, but that value remains hidden from the component where it was originally set

The authentication feature: import React, { useState } from 'react'; let selectedUserByAdmin = ''; const AuthContext = React.createContext({ setSelectedUserByAdmin: () => {}, selectedUserByAdmin, }); export const AuthContextPro ...

Why is it that when accessing the property of an object within a computed object, it returns as undefined instead of the object itself? Which method would be more suitable in this

Salutations. To provide some context, my intention in posing this query is to dynamically render a child component within a form based on the selection made using the <app-selector> Vue component, as straightforward as that. To simplify matters, I ...

Instructions for turning an HTML table cell into an editable text box

Essentially, I'm looking to enable users to click on the table and edit the text within it. I found inspiration from this Js Fiddle: http://jsfiddle.net/ddd3nick/ExA3j/22/ Below is the code I've compiled based on the JS fiddle reference. I tho ...

"Create dynamic tables with AngularJS using ng-repeat for column-specific rendering

I have a model called Item with the following structure: {data: String, schedule: DateTime, category: String} I want to create a report that displays the data in a table format like this: <table> <tr> <th>Time Range</th&g ...

A pattern matching formula to eliminate specific characters from the beginning to the end of a string

I am facing an issue with extracting content from a given string: var string = "From: Sarah<br /> Sent: 10 May 2021 09:45:20</br /> To: Alice<br /> Subject: Meeting Reminder<br /><br /> Hi Alice, <br /> Here is a ...

Show the ajax appended html only after reaching a specific threshold

I am currently utilizing AJAX to fetch additional results from my database. Below is the basic script I am using: $('#loadmorebuilds-div').click(function() { $.ajax({ url: 'includes/loadmorebuilds.php?type=' + type + &ap ...

Simulation of loopback session

Currently, I am utilizing loopback in conjunction with express session to store cartId. However, for the purpose of making my tests function properly, it is essential that I inject cartId into the request session. Within my remote method, I have implemen ...

sophisticated HTML navigation bar

I am looking for a way to create a menu where the drop-down items overlay the rest of the menu when the screen width is small. Here is my current code: nav{ line-height:100%; opacity:.9; }nav ul{ background: #999; padding: 0px; border-radius: 20px; ...

Located at the lower section of the parent container

In my flex container, I have two boxes arranged side by side (collapsing into one column on smaller screens). I've ensured that these boxes have the same height when displayed together, as shown in the image below: https://i.sstatic.net/ZjsfW.png No ...

Using JQuery to switch out images that do not have an ID or class assigned

Currently, I am using a Google Chrome Extension to apply an external theme to a website. Unfortunately, the logo on the site does not have an ID or class that can be used to call it. I am searching for a solution to replace it with a different image. My ...