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.