The error message "Cannot read property '$scope' of undefined" indicates that there is an issue

After receiving HTML content in an Angular app, I inject it into the HTML document but struggle to retrieve it. For example, you can see a minimized code on plunker here and in JavaScript here

Below is my controller:

class ReadCtrl

  constructor: (@$scope, @$rootScope, @$compile, @$sce, @$window, @webService) ->
    @getData()

  getData: ->
    promise = @webService.getBookText()
    promise.then @success, @error

  success: (response) =>
    @$scope.html = response.data
    @$scope.trustedHtml = @$sce.trustAsHtml(@$scope.html)
    console.log $('.book_contents').first().children()

ReadCtrl.$inject = ["$scope", "$rootScope", "$compile", '$sce', "$window", "webService"]
angular.module("bookReader").controller "ReadCtrl", ReadCtrl

The method 'success' saves HTML to the 'trustedHtml' variable, which is then bound to the view:

<div class="br_container">
  <div class="br_source_container" ng-bind-html="trustedHtml">
  </div>
</div>

While the content displays, the line

console.log $('.book_contents').first().children()
returns zero elements. Attempting to insert something like @$rootScope.$digest() throws an error:

Error: [$rootScope:inprog] $digest already in progress

This issue arises from the arrow function => within the method, which compiles to:

  __bind = function(fn, me){ return function(){ return fn.apply(me, arguments); }; };
  this.success = __bind(this.success, this);

Replacing => with -> results in another error:

 TypeError: Cannot read property '$scope' of undefined

This occurs in the first line of the success function. As a result, this is undefined in the success function, likely due to how it is called with a promise.

Using another method involving

$('.br_source_container').html(@$compile(@$scope.trustedHtml)(scope))
leads to similar errors.

Therefore, the challenge lies in obtaining the DOM html of the inserted section.

Answer №1

Resolved the issue using a timeout as suggested by charlietfl. Here's how it worked:

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

What could be causing the slow build time for npm run serve on a Vue.js project?

My Vue.js project was running smoothly until about an hour ago when I noticed that it is now taking a very long time to build. Specifically, it gets stuck at 32% for more than 5 minutes. Does anyone have any suggestions on how to fix this issue? I'm n ...

Exploring PrimeNG's method for expanding and collapsing groups

I'm attempting to incorporate two buttons that can be used to either expand or collapse all the groups in my code utilizing primeNG. Below is the functioning code: PLUNKER <p-dataTable [value]="data" sortField="room" rowGroupMode="subheader" grou ...

Using the Grails asset-pipeline with an external JavaScript library

In transitioning from Grails 2 to Grails 3, I am facing the challenge of managing my JavaScript files with the asset-pipeline plugin. The issue lies in using external libraries such as globalize and ajax-solr, which are large and consist of multiple interd ...

What is the best way to interact with my component in React?

As a newcomer to Reactjs, I have a question regarding my current setup: The components in my project include navComponent.js, stackComponent.js, and nav.js I am trying to pass data from stackComponent.js to navComponent.js so that the nav.js data can be ...

Creating a Dynamic Canvas Rendered to Fit Image Dimensions

I'm struggling with a piece of code that creates an SVG and then displays it on a canvas. Here is the Jsbin Link for reference: https://jsbin.com/lehajubihu/1/edit?html,output <!DOCTYPE html> <html> <head> <meta charset=&qu ...

I'm encountering an issue with my array in JavaScript while using // @ts-check in VS Code. Why am I receiving an error stating that property 'find' does not exist on my array? (typescript 2.7

** update console.log(Array.isArray(primaryNumberFemales)); // true and I export it with: export { primaryNumberFemales, }; ** end update I possess an array (which is indeed a type of object) that is structured in the following manner: const primar ...

Transforming field names in JSON using AngularJS $resource

I am currently working on an AngularJS project that interacts with data through an API. During the implementation of the 'create' functionality using $resource, I encountered a challenge with naming conventions. While I use camelCase, the API onl ...

What are some techniques for preventing Null Pointer Exception errors?

Currently, I am working on a project that involves creating a form with a dropdown field for categories. Based on the chosen category, I need to populate a second dropdown called subcaste using AJAX. To achieve this, I have implemented a method that disab ...

How can you incorporate AJAX to add a paragraph element to your HTML document?

I have encountered an issue with two files in my project. The first file is an HTML document, while the second file is a PHP file called ajax_access_database.php. Originally, I intended for the PHP file to access a database, but complications arose, leadin ...

Should Jasmine recommend decreasing the number of local variables or focusing on improving karma coverage reports?

My Karma coverage report indicates that the local variable is not being covered. Is this a possible issue with the karma-coverage report? Please take a look at the Angular Controller Code below. 'use strict'; angular.module('moduleName&ap ...

I'm attempting to create a button that changes to a bold red color when the condition is met

I am currently working on developing web applications using the Pixabay API. My goal is to allow users to mark an image as a favorite and have the heart icon change color to red accordingly. However, I seem to be facing issues with this functionality. To ...

Type of JavaScript map object

While exploring TypeScript Corday, I came across the following declaration: books : { [isbn:string]:Book}={}; My interpretation is that this could be defining a map (or dictionary) data type that stores key-value pairs of an ISBN number and its correspon ...

Issue with AngularJS service or controller causing map to not update in angular-leaflet-directive

I'm currently working on generating a map by utilizing the Angular-Leaflet-Directive along with data retrieved from 2 distinct Angular services that fetch web services using $resource. The JSON messages returned by these services contain lat/long valu ...

What is the best way to toggle the color of the circle div in the center between yellow and white with every click within the circle?

Up to now, I have successfully accomplished this with just one click. I deleted the lightbulb image const sphere = document.getElementById("sphere"); sphere.addEventListener("click", event => { console.log("You clicked the ...

When React object state remains unchanged, the page does not update automatically

i have a state object with checkboxes: const [checkboxarray_final, setCheckboxarray_final] = useState({ 2: ",4,,5,", 9: ",1,", }); i'm working on enabling check/uncheck functionality for multiple checkboxes: these are ...

Please be patient for the PayPal script to load on the nextjs page

I've encountered an issue with my code that is meant to display PayPal buttons <Head> <script src="https://www.paypal.com/sdk/js?client-id=KEY"></script> </Head> The PayPal buttons are loaded within the ...

Ways to select the initial 10 rows, final 3 rows, and middle 2 rows using Javascript

As a newcomer to Javascript, I have a couple of questions: 1) How can I retrieve the first 10 rows, the last 3 rows, and the 2 rows in the center using the code var firstTable = $('#aaa table').eq(0); 2) Is there a way to create and assign new ...

How do I directly display a variable in index.html using node.js?

Is there a way to retrieve user inputs from the index.html file, process them in Node.js, and then display the result back on the index.html page instead of redirecting to a new page? Form Handling with Express var express = require('express'); ...

Add delayed event listeners to embedded AJAX request beyond function boundaries

I'm working on developing a custom AJAX method extension named getApi that automatically includes my authentication bearer token in the request header. In my code, there is a function called getToken() which retrieves the token either from sessionSto ...

Angular 4: Modifying the URL without the Component being Displayed

I'm currently facing an issue where I am attempting to link a component from one component using routerLink = "selected" const routes: Routes = [ { path: '', children: [ { path: 'account&apo ...