Skipping the use of ng-bind for delayed compilation in Angular

Insight

In order to execute the $compile function after your angular application is up and running, you can utilize the angular.injector method.

angular.injector(['ng', 'late']).invoke(function($rootScope, $compile) {
    $compile(myElement)($rootScope)
}

While this method successfully triggers directives created within the late module, it may not engage any of the ng-bind directives.

Illustration

The initiation of my angular app occurs on a distinct element separate from those requiring compilation.

<div ng-app="test">
</div>

<div id="uncompiled">
{{ $id }}
  <div ng-controller="LateController as cont">
    {{ $id }} {{ "5" }} {{ cont.clicked }}
    <div late-directive="5"></div>
  </div>
</div>

Following the completion of angular bootstrapping, I proceed to establish the necessary modules and directives for elements designated for delayed compilation.

angular.element(document).ready(function() {
  angular.module('late', [])

  angular.module('late').controller('LateController', function($scope) {
    console.log('Creating controller', $scope)
    $scope.lateController = true
    this.clicked = 6
  })  

  angular.module('late').directive('lateDirective', function() {
    console.log('Generating directive')
    return {
      restrict: 'A',
      template: '<span>INNEREST {{ $id }}</span> COMPILED LATE!!! {{ $id }} {{ cont.clicked }}',
    }
  })

  angular.injector(['ng', 'late']).invoke(function($compile, $rootScope) {
    console.log('Injecting')
    var el = angular.element(document.getElementById('uncompiled'))
    $compile(el)($rootScope)
  })
})

Experiment with the code or view the result.

If you observe closely, while the directive templates are successfully embedded, the {{ }} ng-binds do not get substituted.

Inquiry

Why do certain directives function correctly while others do not?

How can all directives be effectively executed within the deferred $compile process?

Answer №1

The reason behind this phenomenon can be seen when we insert a single line of html code. By including another element within the LateController

<input ng-model="cont.text" />

the entire example functions as expected. Why does adding an ng-model impact the other directives? This behavior indicates that the other directives are being executed, but their values are not being displayed on the screen.

In a typical angular application, once everything is configured, the application goes through a $digest cycle. However, when using $injector.invoke, this cycle doesn't occur automatically.

The reason why the example started working after adding the ng-model is because ng-model triggers a $digest.

Resolution: Include $rootScope.$digest() at the end of the invoke.

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

Getting a portion of a div ID through jQuery or JavaScript

In the contents of my webpage, there is a specific division element that appears as follows: <div id="entry-7265">...</div> Is there a way to extract only the numerical part of this div's ID using either jQuery or JavaScript? I am not int ...

DNN Unveils New "Exit Confirmation" Pop-up Feature When Clicking External Links

Greetings fellow beginners! I've been struggling to make some changes on our DNN site (Evoq 8.5) with no success so far. The issue at hand is that we have links throughout our entire website that follow this format: <a href="www.site.com" class="e ...

Circular reference in Angular/TypeScript

I encountered a circular dependency issue in my Angular project and tried various solutions, including exporting all dependent classes from a "single file" as suggested here. Unfortunately, this approach did not work for me. I then explored other solutions ...

What is the most effective way to iterate through an array of objects and retrieve the results in a key-value format?

I am dealing with an array of objects that may seem a bit complex initially, but I will simplify it as much as possible. Each object in the array has properties like Engineering, Environment, and others, each containing a sub-object called radars. The rada ...

Is it possible to store a value of negative zero in MongoDB?

Is there a concept of negative zero in JavaScript? How does MongoDB handle this particular value? ...

Ajax continues to repeatedly redirect to the PHP page

I currently have a Shopify store and I am looking to incorporate a form on the product page. However, I am facing an issue where when I try to submit the form using AJAX with an external link, it redirects to the external page instead of staying on the cur ...

Create a PDF document with pdfkit and stream it to the browser in a Node.js Express application

I am currently using pdfkit to create a PDF file and I would like to send this PDF directly to the browser. However, I am encountering an error message stating "TypeError: listener must be a function", Additionally, the file is being generated in m ...

Using JavaScript/jQuery to analyze POST values just before submission

Currently facing a dilemma as my company is in the process of redesigning its website. I find myself stuck trying to come up with a temporary fix for an issue on the existing site. The solution requires the use of JavaScript or jQuery. The problem arises ...

How to Use Jquery UI Datepicker

Currently, I am delving into the world of JavaScript and have grasped some understanding of it. As I created a webpage with a date entry field, I require a calendar feature to enable date selection. The jquery UI datepicker (http://jqueryui.com/datepicker) ...

Experimenting with Vuejs by testing a function that delivers a Promise upon the execution of the "Created" hook

In my Vuejs application, I have the following script written in Typescript: import { Foo, FooRepository } from "./foo"; import Vue from 'vue'; import Component from 'vue-class-component'; import { Promise } from "bluebird"; @Component ...

Node.js: Managing multiple occurrences of the same event name for testing purposes

When it comes to unit testing using mocha, I am looking for a way to set up an asynchronous queue for handling events. Previously, I used a once() Promise to wait for events like this: import EventEmitter from 'events' import { once } from ' ...

Retrieving nested array elements in MongoDB using parent ID element (JavaScript)

Suppose I have a MongoDB collection structured as follows: _id: ObjectId(" <a objectid> ") id: " <a userid> " __v: 0 subscribedTo: Object Regardless of whether or not Mongoose is being used, how can I execute a query to acc ...

Navigating the world of CSS and custom directives in AngularJS can be overwhelming at first, but

Exploring a custom directive in angularjs: .directive('myDir', function() { return { restrict: 'E', template: "..." } }) When considering the <my-dir></myDir> tag, it appears to lack any default styling (or is ...

The HTML previous function on the table data element is returning a value of null or being

Within a <table> that contains checkboxes in the last column, I am trying to create a JavaScript function that will sum up the values of the previous two <td> elements when a checkbox is selected. However, I am facing difficulty in locating the ...

Tips for obtaining intellisense for the value in a readonly string array property within an object without relying on generics

Keeping it brief and to the point. What is the reason behind this? type ReadonlyStringArray = readonly string[] type TEnumGeneric<EnumIsh extends ReadonlyStringArray> = { type: "enum", values: EnumIsh } type TEnumImplied = { t ...

Understanding the essentials of connecting HTML and Node.js through communication

I'm brand new to web application development and I've hit a roadblock in setting up the backend for my HTML file. I've managed to create a sleek user interface using HTML and JavaScript, and I've been studying tutorials on node.js. Howe ...

Update app content without requiring users to download a new APK

Hey there, I'm new to all of this so I appreciate your patience. I'm working on a video based app and I'm wondering how I can add new videos/content to the app without having users download a new apk. I know I need to host the app on a data ...

Having trouble getting CSS3 Keyframes to function properly?

Check out the following code snippet: .startanimation { height: 100px; width: 100px; background: yellow; -webkit-animation: animate 1s infinite; } @-webkit-keyframes animate { 100% { width: 300px; height: 300px; } ...

The status of the xmlhttp object remains unchanged

I was attempting to create an application showcasing the use of AJAX. Being new to AJAX, I couldn't pinpoint the error in my code. The XMLHttpRequest object is being created, but nothing else seems to be working. The ready state doesn't change to ...

Grabbing a specific section of a URL in AngularJS: Tips and Tricks

I have a URL that appears as: www.ccadmin/admin.jsp?id=Aetna834 Is there a way to extract the value Aetna834 from it? ...