I recently encountered a component code that sets the HTML content using
$scope.htmlContent = $sce.trustAsHtml(content)
. Subsequently, it calls a function within a $timeout
to search for an element inside that content using $element.find('.stuff')...
This code is contained within a $scope.$watch
in the $onInit
function.
My concern is whether the DOM element for the content will be completely rendered before the $element.find
is executed. Is there a more reliable approach we can take?
Here is the key code snippet for reference:
(function() {
'use strict';
angular.module('mymodule').component('exampleComponent', {
templateUrl: 'path/template.html',
bindings: { content: '<' },
controller: ExampleComponentCtrl
});
function ExampleComponentCtrl($element, $sce, $scope, $timeout) {
this.$onInit = function() {
$scope.$watch(function() {
return $sce.valueOf(self.content);
}, function() {
// irrelevant operations that generate a variable 'content' containing HTML code
$scope.htmlContent = $sce.trustAsHtml(content);
// Using $timeout to ensure inner HTML injection is complete
// so that we can effectively locate `.file-link` elements
$timeout(function() { $element.find('.stuff').each... });
});
};
}
)();
HTML template structure:
<pre ng-bind-html="htmlContent"></pre>