Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

$compile not compiling html string - angularJs

I'm trying to compile some raw html with angular directives with the properties over scope but it is not working as expected. Here is an snapshot of simple code I'm running on a breakpoint in console.

console

$scope.scopeString = "scope string value";

"scope string value"


$scope.scopeArray = [1,2,3]

(3) [1, 2, 3]


$compile(`<div>{{scopeString}}</div>`)($scope).prop('outerHTML')

"<div class="ng-binding ng-scope">{{scopeString}}</div>"


$compile(`<div><div ng-repeat="item in scopeArray">{{item}}</div></div>`)($scope).prop('outerHTML')

"<div class="ng-scope"><!-- ngRepeat: item in scopeArray --></div>"

Can anyone tell what am I doing wrong?

like image 319
pranavjindal999 Avatar asked Jul 26 '26 05:07

pranavjindal999


1 Answers

Scope bindings are calculated on digest cycle. Retrieving HTML from the element immediately doesn't leave it a chance to interpolate bindings.

When code is executed inside digest cycle (e.g. a controller) it can be

var $el = $compile(`<div>{{scopeString}}</div>`)($scope);
$timeout(() => {
  console.log($el.prop('outerHTML'))
});

When it is executed outside digest, it is

var $el = $compile(`<div>{{scopeString}}</div>`)($scope);
$scope.$apply();
console.log($el.prop('outerHTML'))
like image 144
Estus Flask Avatar answered Jul 27 '26 19:07

Estus Flask