简体   繁体   中英

Use part of an HTML file in templateUrl

Is there a way to use only part of a file as your directive's templateUrl ? For example, if I have a file

<input type="text" data-name="first-name" />

<input type="text" data-name="last-name" />

<input type="text" data-name="address" />

etc.

is there a way for Angular to pull out only the "first name" input tag or only the "last name" input tag, as opposed to using the entire file?

I want to be able to have multiple directive's HTML content as a single HTML file, as having just one line of code seems like a waste of a file (UNIX philosophy has its limits). Also, I might want to concatenate these templateUrl files as part of my minification process, and I want to know Angular won't use the entire file for each directive.

There's no way to use just part of a template url; the entire thing gets pulled in and compiled.

For short templates, I've found that in lining the template with the directive can be a best practice. The reduction in context switching when it's only a little html tends to be worth it, imo.

This can be done by changing the tag from

templateUrl: 'foo.html' 

to

template: '<input type="text" data-name="address" />' 

Hope that helps!

AngularUI has this functionality. In its UI-Utils package, there is the ui-include directive. This is exactly like the ng-include directive, except that it allows an extra attribute, fragment , which includes a part of a page, rather than a whole page, into itself.

The sample code on the AngularUI UI-Utils page demonstrates quite well:

<ui-include src="'my/url/to/partial/file'" fragment="'#id-to-fragment'"></ui-include>
<!-- Don't forget to quote string literals! -->
<!-- Don't forget to include jQuery if you need full selector support! -->

Of course, you're probably including jQuery already. :)

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