AngularJS Example
Custom Interpolation Symbols Directive. For changing the symbols dynamically. There are easier ways to change it across the whole app by configuring the $interpolate provider.
by Collin Donahue-Oponski
November 07, 2013
HTML
<div ng-app="customInterpolationApp">
<div ng-controller="DemoController as demo" underscore-template>
<%= demo.label %>
<br />
<%- demo.evil %>
</div>
</div>
CSS
</style> <!-- Ugly Hack to make remote files preload in jsFiddle --> <script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/angularjs/1.2.0-rc.3/angular.min.js"></script> <style>
JavaScript
var customInterpolationApp = angular.module('customInterpolationApp', []);
customInterpolationApp.directive('underscoreTemplate', function ($parse, $compile, $interpolate) {
return {
restrict: "A",
link: function(scope, element, attrs) {
var startSym = $interpolate.startSymbol();
var endSym = $interpolate.endSymbol();
var parsedExp = $interpolate(element.html().replace(/<%=/g, startSym).replace(/<%-/g, startSym).replace(/%>/g, endSym));
scope.$watch(parsedExp, function(newValue) {
element.html(newValue);
});
}
}
});
customInterpolationApp.controller('DemoController', function DemoController() {
this.label = "This bindings is brought to you by <%= %> interpolation symbols.";
this.evil = decodeURIComponent("%3E%3Cscript%3Ealert(%22evil.%22)%3C%2Fscript%3E");
});