Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I make angular.js reevaluate / recompile inner html?

I'm making a directive that modifies it's inner html. Code so far:

.directive('autotranslate', function($interpolate) {     return function(scope, element, attr) {       var html = element.html();       debugger;       html = html.replace(/\[\[(\w+)\]\]/g, function(_, text) {         return '<span translate="' + text + '"></span>';       });       element.html(html);     }   }) 

It works, except that the inner html is not evaluated by angular. I want to trigger a revaluation of element's subtree. Is there a way to do that?

Thanks :)

like image 296
kornfridge Avatar asked Jan 31 '14 18:01

kornfridge


People also ask

What is attrs in AngularJS?

Using attrs you are able to access the attributes defined in your html tag like <fm-rating ng-model="$parent.restaurant.price" symbol="$" readonly="true"> So in this case you will have access to the symbol and readonly attributes.

How to make custom directive in AngularJS?

Define custom directive to handle above custom html tags. var mainApp = angular. module("mainApp", []); //Create a directive, first parameter is the html element to be attached. //We are attaching student html tag. //This directive will be activated as soon as any student element is encountered in html mainApp.

What does $compile do in AngularJS?

Compiles an HTML string or DOM into a template and produces a template function, which can then be used to link scope and the template together.

What is restrict in AngularJS directive?

Note: When you create a directive, it is restricted to attribute and elements only by default. In order to create directives that are triggered by class name, you need to use the restrict option. The restrict option is typically set to: 'A' - only matches attribute name.


1 Answers

You have to $compile your inner html like

.directive('autotranslate', function($interpolate, $compile) {     return function(scope, element, attr) {       var html = element.html();       debugger;       html = html.replace(/\[\[(\w+)\]\]/g, function(_, text) {         return '<span translate="' + text + '"></span>';       });       element.html(html);       $compile(element.contents())(scope); //<---- recompilation      }   }) 
like image 100
Tasnim Reza Avatar answered Oct 05 '22 21:10

Tasnim Reza