Revise directive following the dynamic addition of elements

My Objective:

I aim to utilize directives for creating custom elements and dynamically inserting them into the view at various points in time.

The Challenge:

Upon dynamically adding custom elements to the view, they appear as raw HTML without the directive updating them as expected.

For Example:

Consider a custom element -> <ell></ell>. When I manually input <ell></ell> in the HTML, the directive functions correctly by generating 4 divs, each with the 'block' class. For instance ->

<div class="block"></div>
.

However, when I define the inner HTML of a div ->

<div id="level" ng-bind-html="piecesInPlay"></div>
from a string within the controller and update that string, the directive does not react to the <ell></ell> tag.


Below is the relevant code snippet:

Angular Directives: (a directive for each element in scp.pieces[] array)

app.directive('sqr', function() {
  return {
    restrict: 'E',
    template: tetris.templateString,
    link: tetris.randColor
  };
});

Angular Controller:

app.controller('levelCtrl', ['$scope', function(scp) {
  scp.pieces = ['<ell></ell>', '<r-ell></r-ell>', '<sqr></sqr>', '<zee></zee>', '<r-zee></r-zee>', '<tee></tee>', '<line></line>'];
  scp.piecesInPlay = '<ell></ell>';
  
  scp.generateNewPiece = function() {
    var min = 0, max = 6;
    var randPiece = Math.floor(Math.random() * (max - min + 1)) + min;
    
    scp.piecesInPlay += scp.pieces[randPiece];
    return scp.pieces[randPiece];
  };
  
  // generates a random piece and adds it to the pieces in play
  scp.generateNewPiece();
}]);

HTML:

<div id="level" ng-controller="levelCtrl" ng-bind-html="piecesInPlay">

</div>

Answer №1

1) Despite returning a string, the function itself does not do anything with it. return scp.pieces[randPiece];

2) It is essential to compile the string into an element and then append it.

     var newElement= $compile(template)($scope);
     $element.append( element );
     $scope.$digest();

To make Angular recognize the new directive you have added, you must compile it first, followed by digesting to propagate the command for child scopes to take effect.

UPDATE:

Following the feedback received, this inquiry aims to bind to compiled "directive elements" in the DOM from an array, without the need to continuously append and digest a new scope. The goal is to invoke controllers directly from HTML strings.

In my opinion, achieving this directly may not be feasible. A more efficient approach would involve having an array of strings containing the controller names of your game pieces.

Then, within ng-repeat, manually link a controller based on that particular string.

<div class="my-pieces" ng-repeat="controllerName in board.activeControllerStrings">

<div ng-controller="{{controllerName}}"></div>

This method allows for dynamic data binding while bypassing the directive aspect and instead incorporating controller functionality into the elements manually.

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

Embedding a video element results in an unexpected increase in height

When I insert an HTML5-Video element into a div, it results in the wrapper having a height larger than the video itself. The wrapper is 7px taller than the actual video source, without any min-height set. Check it out! (Scroll down to the Video) The vide ...

Custom search filter in ng-grid using a customized cellTemplate

I am facing an issue with the ng-grid search filter on a column that references a cellTemplate. In my data object, there are multiple fields. One of these fields is an array and I have used cellTemplate to create a div with ng-repeat in order to display t ...

When adding values, they remain in their original positions

I am populating a select dropdown with options using AJAX. These options are added based on the selection made in another dropdown. The first function that appends the data: var appendto_c = function(appendto, value, curcode) { appendto.append("& ...

When combining <a> with the class line-through, the line does not appear

I am currently utilizing a class to replace the deprecated strike in HTML: .entfall { text-decoration: line-through; } However, when using Firefox 38.x and the following code: <span class="entfall"><a href="some link">text</a></span ...

Can you tell me the specific location in the CSS where this logo image is defined?

I've been working on a website at http://onofri.org/WP_BootStrap/ and I'm facing an issue. When using FireBug, I can't seem to locate where in the CSS the image logo.png is defined (this is the small image in the upper-left corner of the the ...

smoothly hide the dropdown menu when a link is clicked with a transition effect

I am struggling with two bugs in my dropdown menu that I can't seem to fix. The navigation links on my homepage take users to different sections of the page instantly when clicked. However, the issue arises when the dropdown menu does not close after ...

Disable the click event using jQuery

$("button").click(function (){ $("<button>Start</button>).appendTo('main'); }); The code above introduces a functionality where clicking a button generates another button dynamically. However, each subsequent click kee ...

Is it possible to create HTML tables without including paragraphs within the cells using docutils rst2html?

If my input rst file looks like this: +--------------------------------+ | Table H1 | +-------------+------------------+ | Table H2a | Table H2b | +=============+==================+ | a1 | b1 | +------ ...

Unwrapping the potential of $http promise in AngularJS

Starting with AngularJS, I am curious about how to handle the response of "response.data" as a typical function. The issue arises because when using $http, it generates a promise, causing the function to finish execution before returning the server respons ...

Issue encountered when attempting to include jquery.min.js due to a jquery conflict

I've been experimenting with the jquery.scrollableFixedHeaderTable.js extension in order to create a table header that remains fixed as you scroll through the table. However, when I attempt to incorporate jquery.min.js for a tooltip plugin, the scrol ...

Skipping validation while navigating back on SmartWizardIf you need to bypass validation during backward

Looking for assistance with Jquery smartwizard? Check out the link. I want to disable validation when a user clicks on the "Previous" button in any step, except for the first step where the Previous button is disabled by default. Below is my JavaScript co ...

Showcasing diverse content with an Angular Dropdown Menu

I'm currently developing an angular application, and I've encountered a difficulty in displaying the user's selection from a dropdown menu. To elaborate, when a user selects a state like Texas, I want to show information such as the period, ...

What is the process for updating an existing Ionic app to a newer version?

Hey, I'm currently customizing a template I found on CodePen. Here is the link: "http://codepen.io/fairupoyil/pen/oXrXjX?editors=100" I noticed that the version of the template is outdated, so I updated the JS file to a newer version. However, now I ...

Using HTML5's getCurrentPosition function with Meteor

Attempting to utilize the html5 geolocation api within Meteor. Executing: navigator.geolocation.getCurrentPosition(handle_geolocation_query); in my javascript code but encountering issues - suspect it could be tied to the restrictions on timing ( ) enfo ...

Angular login/signup modal/dialog component for seamless user authentication

Currently, I am working on adding a login/signin dialog to my app similar to the one used by Medium. After doing extensive research online, I have decided to use the $modal from angular ui-bootstrap for this. Can anyone please recommend a tutorial that wil ...

Exploring MySQL: Retrieving Data Efficiently while Monitoring Server Performance

Currently, I am in the process of developing a web application that communicates with a MySQL database to send and receive data. My goal is to display any changes made in the database on the web page as quickly as possible. My main concern now is determin ...

Styling content in a CSS file and then rendering it as a

My current project involves converting a webpage into a PDF file and I am using @page @bottom-left to insert text in the bottom left corner. @page {size: portrait A4; @bottom-left {content: "Some text to display at the bottom left. Some additional text ...

Send various pieces of information using Jquery/Ajax

I have encountered a challenge with my script - it currently only sends one value to the requested URL, but I now need it to handle two values. Unfortunately, I haven't been able to figure out how to do this. Each checkbox on the page is paired with ...

Creating a color icon for StackExchange using HTML

I am currently working on building my personal website. I am looking to include a link to my Stack Exchange profile on my site using the Stack Exchange icon. However, the icons available in Font Awesome are grayscale and not colored like other icons such a ...

What are the steps to embedding a Facebook video on a website?

Could someone please help me with embedding a Facebook video? I tried following the instructions provided at: https://developers.facebook.com/docs/plugins/embedded-video-player Unfortunately, I'm having trouble getting it to work. Here is the sourc ...