2

Is there a way to prevent interpolation on a div? I want to grab the raw html from it and interpolate manually by injecting $interpolate like this:

$scope.report = $interpolate($("#myDiv").html())($scope);
adam0101
  • 29,096
  • 21
  • 96
  • 174

2 Answers2

4

Use ngNonBindable directive. Taken from the docs:

<div>Normal: {{1 + 2}}</div> // => Normal: 3
<div ng-non-bindable>Ignored: {{1 + 2}}</div> // => Ignored: {{1+2}}

However, beware that this probably won't compile other directives present in that element.


Another option (which is the most correct in my opinion) is to create a directive and capture the content of the element in the compile phase, and then only interpolate it when you need:

app.directive("myDirective", function( $interpolate ) {
  return {
    compile: function( tElement ) {
      var raw = tElement.html();
      return function( scope, element ) {
        var interpolated = $interpolate( raw )( scope );
        // do something with it
      };
    }
  };
});
gustavohenke
  • 40,997
  • 14
  • 121
  • 129
1

You can use inline templates declared using script tag (https://docs.angularjs.org/api/ng/directive/script)

   <script type="text/ng-template" id="myDivTemplate">
      Hello my name is {{name}}
  </script>

Then interpolate it as

$scope.report = $interpolate($("#myDivTemplate").html())($scope);
Deepak N
  • 2,561
  • 2
  • 30
  • 44
  • Since you already defined the template, wouldn't it be better to grab it from the template cache? `$interpolate($templateCache.get('myDivTemplate'))($scope);` – adam0101 Sep 18 '14 at 16:31
  • Yes. This way you won't feel guilty of doing DOM manipulation anywhere that's not inside a directive. Also, even better is to use `$http` with `cache: $templateCache`, because this way you don't have to assume that the template _will always_ be in the page. – gustavohenke Sep 18 '14 at 16:39
  • Using `$templateCache.get('myDivTemplate')` would be more cleaner approach – Deepak N Sep 18 '14 at 16:41