简体   繁体   中英

Angular.js template parsing hook

I'm wondering if there is a template parsing hook in Angular, that you can use globally or in specific controllers.

What I want to do is to implement a language and device specific (multidimensional) theme loader, that will dynamically grab any ressource link (img-tags, inline-styles) and redirect to the specific resource.

For example: Someone implemented a template that shows some image:

<img src="images/my-super-image.jpg">

Now I want to grab the template and change the ressource to it's language specific correspondant:

<img src="theme/en_us/lowres/my-super-image.jpg">

The following things are important for me:

  • The one who generates the template doesn't need to take care of the themes, just uses the ressource as given in the first example
  • I don't want to use a directive, I want a global (App specific) solution --> best would be to have it in the run()-function of the app
  • I don't want to use look-up tables for the ressources, just want it to be highly dynamical

At the moment I'm not quite sure where to place such a parse-hook-function, nor how to get access to the current templates used on a page, to manipulate them before Angular provides them to the DOM.

I used some dirty hack, but I'm unhappy with it, because it will only be applied, when templates are already rendered and provided:

$(document).bind('DOMNodeInserted', function(event) {

  if(angular.isDefined(event.originalEvent.originalTarget.innerHTML)) {
    event.originalEvent.originalTarget.innerHTML = String(event.originalEvent.originalTarget.innerHTML).replace('src="images','src="' + imgPath);
  }
});

Do you have any idea of how to do it? Thank you, guys!

Btw. I'm pretty new to Angular, so if you'd please be very descriptive, that would be kind. Thanks again.

You can use compile, Since angular only allow directives to modify DOM you need to create a directive Here is an example

app.directive('myApp', function() {
return {
restrict: 'A',
replace: true,
link: function(scope, element, attrs) {

},
compile: function(tElement, tAttrs, transclude) {
tElement.find('img')[0]['src'] = "theme/en_us/lowres/" + tElement.find('img')[0]       ['src'].split('/')[tElement.find('img')[0]['src'].split('/').length - 1];
 }
 };
 });

Plunker

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