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

Is it accurate to consider all JavaScript code and variables as inherent properties of an execution context?

It's worth considering that everything in JS code can be viewed as a property of an execution context, whether it's a global, function, or eval() execution context. Why is this the case? Each execution context has its own unique lexical and v ...

Placing a Div wrapper around the contents of two corresponding elements

I am currently attempting to wrap a div with the class name 'wrapped' around two other divs containing innerHTML of 'one' and 'two'. <div class='blk'>one</div> <div class='blk'>two</di ...

Can you demonstrate how to repeatedly increase a running total using a for loop until the loop ends?

Looking at the for loop. The goal is to have the interest calculated based on the latest value variable. Currently, the script generates the same interest rate and value for each year. What I desire is for it to use the previous value variable to determine ...

Receiving a commitment from an Angular Resource

When working with $resource in Angular for CRUD operations, I'm encountering some confusion regarding the usage of different resource methods. From what I've observed, the "regular" methods like save() and get() appear to execute synchronously. ...

Combining arrays based on a key in Node.js

I have the following two objects that need to be merged: [ { "response_code": 1, "response_message": [{ "a": 1000, "b": 1000001, "c": 10000002 }] }] [ { "response_code": 1, ...

Convert time display to a 24-hour format using JavaScript

I managed to convert the time format from GMT to my browser's local time using the following JavaScript code: var newDate = new Date(timeFromat); timeFormat = newDate.toLocaleString(); Now, I want to change the time format to a 24-hour clock format ...

Trying to access the 'style' property of a null value is causing an error

Although I have come across several questions related to this particular error, unfortunately, none of them provided a solution. Below is the HTML code: <!DOCTYPE html> <html> <head> <title>ChatRoom</title> <link ...

Button react-native press following textInput within scroll view aware of keyboard movements

I'm currently facing an issue where I have a TextInput and a button nested inside a KeyboardAwareScrollView. The goal is for the user to input some text and then tap the button created using TouchableOpacity, which should send the inputted text forwar ...

Retrieve the file's source and name using AngularJS

Is it possible to retrieve the name, path, and size of a selected file in an input field using AngularJS before uploading it? <input type="file" ng-model="fileContent" on-read-file="showContent($fileContent)" /> $scope.showContent = function($fileC ...

Picture failed to load

I am struggling to get an image to display on my webpage, as only the alt text is appearing. Here is the code I am using: return ( <> <div className="container my-5"> <div className="row ju ...

Is there a way to determine the dimensions of a pdf file using javascript and capture a snapshot of it for showcasing on a website?

I'm fairly new to HTML/CSS and haven't delved into javascript yet, but I have a good understanding of reading other people's code. Currently, I'm putting together my portfolio website and would like to include my resume on the page in a ...

Value binding in Angular being passed to ng-click function rather than the actual value

An HTML link is causing me some trouble: <div class="menu-item" ng-repeat="pageName in pages"> <a ng-click="routing.open('{{pageName}}')">{{pageName}}</a> </div> When clicked, this link triggers the 'open' ...

Find the nth element of an array using Javascript's map function

Recently, I took on the challenge of learning Javascript independently and came across a rather complex task. I have an array with 18 labels and another 1D array containing all the values. Each label index corresponds to every nth element in the array. F ...

Error: Uncaught TypeError when using a for loop in Vue and GraphQL

I encountered a TypeError while attempting to iterate through a GraphQL query in my Vue project. The script snippet in question is as follows: <script> import { useQuery } from "@vue/apollo-composable"; import gql from "graphql-tag&qu ...

Unauthorized access for POST request in WooCommerce API: 401 error

Let's start by examining the complete code to better understand the issue at hand. Here is the WooCommerce API authentication using the consumer key and secret from the file checkout.ts: this.WooCommerce = WC({ url:"http://localhost/ ...

Warning: Potential Infinite Loop when using Vue JS Category Filter

I developed a program that filters events based on their program and type. The program is working correctly, however, an error message stating "You may have an infinite update loop in a component render function" keeps popping up. I suspect that the issue ...

getting information from component in NextJS

Apologies if this question is too basic. I recently started my journey into learning React and NextJS. I am working on a simple application that fetches data and displays it on the Home page. In my component file, I have two functions. This component file ...

Having trouble getting my subarrays to push correctly into the parent array in ReactJS. What am I doing wrong

I am currently working on implementing the bubblesort algorithm using ReactJS. My state includes an array of 3 objects initially sorted in descending order by the 'num' property. I have a button on my interface that triggers the bubblesort functi ...

Transform spaces into %20 from an HTML input field by utilizing JavaScript or jQuery

Hi there, I'm encountering an issue with the input field on my website where users can enter search terms. I am currently extracting the user's input value and adding it to a URL string. jQuery("#searchButton").click(function(){ var simpl ...

Customize the URL path in Next.JS according to the user's location

My Next JS website is hosted on the domain abc.com. I would like the site to automatically detect a visitor's location, retrieve their country code, and then redirect them to abc.com/country_code. ...