简体   繁体   中英

What is the correct way to import and compile external HTML in an Angular controller?

I'd bet this question is already answered somewhere, but I'm coming up empty.

I'm using Angular 1.5.7 and wanting to import some external HTML, within my project, into a component controller (to use in a tooltip), and I can't figure out how to do it.

My structure within a folder is simply like this:

  • component.js
  • component_template.html
  • other_html.html

I've tried the following, using WebPack with the html and ngTemplate loaders (configured in my webpack config): Above my controller declaration, I add

import other_html from './other_html.html';

which is exactly how I get the template for the view (and which works with no further ado):

import component_template from './component_template.html';
angular.module(module).component('name', {templateUrl: component_template}, ...);

Inside the component controller, I've tried various combinations of $sce.trustAsUrl, $sce.getTrustedHtml, and $sce.getTrustedUrl to unwrap the content of my external HTML (in the variable 'other_html') as a string, but frankly these things just confuse me and the documentation doesn't help. It also seems that I'll need to compile the resulting string against the scope of my controller, but I need an HTML string first (I keep ending up with a URL string).

Can anyone demonstrate for me the best way of doing this, with or without relying on WebPack and the html and ngTemplate loaders in the process?

Thanks

Answering my own question. Not entirely my perfect solution, because I'm not compiling any values from my imported HTML, so I'm breaking it up to control as smaller fragments.

First off, I shouldn't have been using ngTemplate in the mix for this purpose. Secondly, the way around that is to prefix your loader chain with an exclamation point, to override the default from your webpack config.

So, this works to provide me with the string I need:

var other_template = require('!html!./other_template.html');

Since I'm using the string to populate a tooltip (jQuery tipso with a wrapping directive) and requires values only available in my component's $onInit callback, I don't think I even have the chance to compile it against my scope before it ends up as output. But in other cases, I'm sure I could compile it and have things work as expected.

Hope maybe this helps others.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM