Angularjs uses custom interpolation characters for scope

I currently have an underscore.js template that I would also like to use with angular and can still use with underscore. I was wondering if it is possible to change the beginning and end characters of interpolation for a specific area using a directive, for example:

angular.directive('underscoreTemplate', function ($parse, $compile, $interpolateProvider, $interpolate) { return { restrict: "E", replace: false, link: function (scope, element, attrs) { $interpolateProvider.startSymbol("<%=").endSymbol("%>"); var parsedExp = $interpolate(element.html()); // Then replace element contents with interpolated contents } } }) 

But it spits out a mistake

Error: unknown provider: $ interpolateProviderProvider <- $ interpolateProvider <- underscoreTemplateDirective

Is $interpolateProvider available only for module configuration? Would a better solution be to simply replace the string to change <%= to {{ and %> to }} ?

In addition, I noticed that element.html() avoids < in <%= and > in %> . Is there a way to prevent this auto-escaping?

+6
source share
1 answer

Well, you have a couple of problems here, but I found a solution for you .

Demo

http://jsfiddle.net/colllin/zxwf2/

Problem 1

Your < and > characters are converted to &lt; and &gt; , so when you call element.html() , you won’t even find an instance of < or > in that line.

Problem 2

Since the $interpolate service has already been "provided" by $interpolateProvider , it looks like you cannot edit startSymbol and endSymbol. However, you can convert your custom startSymbol and endSymbol to angular start / end characters dynamically in your binding function.

Decision

 myApp.directive('underscoreTemplate', function ($parse, $compile, $interpolate) { return { restrict: "A", link: function(scope, element, attrs) { var startSym = $interpolate.startSymbol(); var endSym = $interpolate.endSymbol(); var rawExp = element.html(); var transformedExp = rawExp.replace(/&lt;%=/g, startSym).replace(/&lt;%-/g, startSym).replace(/%&gt;/g, endSym); var parsedExp = $interpolate(transformedExp); scope.$watch(parsedExp, function(newValue) { element.html(newValue); }); } } }); 

Alternatives

I'm not sure how, but I'm sure there is a way to create my own custom $interpolate service using $interpolateProvider (after setting it up for underline tags).

+2
source

Source: https://habr.com/ru/post/952391/


All Articles