3

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?

2
  • What's the interpretion of '$compile(<div>{{scopeString}}</div>)($scope).prop('outerHTML')'? Commented Aug 24, 2017 at 10:58
  • Could you add more information, not clear Commented Aug 24, 2017 at 10:59

1 Answer 1

3

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'))
Sign up to request clarification or add additional context in comments.

4 Comments

I was doing this in an existing digest cycle i.e. controller but I don't understand why do I have to let the current cycle complete to get the compiled html. I don't find explanation for it in documentation also..
Because the expression will be calculated at some point during current digest, but you need to wait until this moment. This can also be done with $$postDigest hook that exists for this purpose ($$ indicates that it's undocumented and you should know what you're doing): $scope.$$postDigest(() => { console.log($el.prop('outerHTML')) })
$compile definition- Compiles an HTML string or DOM into a template and produces a template function, which can then be used to link scope and the template together. I thought template function returned by $compile when called with scope will return the final compiled html. At least the definition seems to imply so. Anyways thanks a lot for help !!
As it appears, it returns HTML element that will be filled with interpolated values soon (during a digest). You're welcome.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.