drakkanraz
drakkanraz

Reputation: 361

How do you compile a template in a directive before sending it to the DOM?

HTML

<body ng-app="myApp">
  <div ng-controller="myController">
    <my-template src="https://plnkr.co/img/plunker.png"></my-template>
  </div>
</body>

JS

myApp.directive('myTemplate', function() {
  return {
    scope: {src: '@'},
    template: '<img src="{{src}}"></img>'
  }
});

In my example plnkr, I have an image that is loaded dynamically from a directive template. If you look at the console when you run, you can see an error trying to load "https://run.plnkr.co/xLToRcEuT2Xr8he7/%7B%7Bsrc%7D%7D", which is the unresolved version of the template (%7B%7Vsrc%7D%7D = {{src}}). This is then picked up by angular as a binding and the correct img is loaded.

The code works, but I don't like having errors lying around. I also don't need the bindings in the template hanging around once it's been resolved in the directive, as there is already a binding on the parent element and the underlying children will never change independently.

Is there a way to compile the template before sending it back to the DOM to a) remove the bindings and (primarily) b) avoid this error.

Upvotes: 2

Views: 421

Answers (1)

dewd
dewd

Reputation: 4429

If you want the {{src}} to bind once only, prefix it with a double colon ie {{src}} becomes {{::src}}. Also, add ng-src instead of src to the image ie <img ng-src={{::src}} />

Upvotes: 1

Related Questions