Search code examples
javascriptangularjsangular-translate

Using "<" or ">" as part of parameter value in angular translate and displaying in textarea as ng-model


I have an angular translate string with a parameter. The parameter name can also be of the form <test>. When the translate is displayed in a textarea, we end up seeing &lt;test&gt; instead of <test>. Is there a way to make it appear as <test>.

The angular translate file is:

"MESSAGE_KEY": "Display {someParam} displayed",

The message is:

var message = $filter('translate')('MESSAGE_KEY',
                {someParam: '<test>'},
                'messageformat');

What I see in the textarea when I use the message as the ng-model is

&lt;test&gt;

Note 1: It will be tricky to use the contenteditable for us for various reasons Note 2: We have set the sanitization strategy to be as below

$translateProvider.useSanitizeValueStrategy('escapeParameters', 'sanitizeParameters');

Solution

  • Edit: Have included a working snipped. Run the code snippet to view the working sample.

    var translations = {
      MESSAGE_KEY: "Display {{someParam}} displayed"
    };
    
    var app = angular.module('AsdDTestApp', ['pascalprecht.translate']);
    
    app.config(['$translateProvider', function ($translateProvider) {
      $translateProvider.translations('en', translations);
      $translateProvider.preferredLanguage('en');
      // Enable escaping of HTML
      $translateProvider.useSanitizeValueStrategy('sceParameters');
    }]);
    
    app.controller('Ctrl', ['$scope', '$filter', function ($scope, $filter) {
      var vm = this;
      vm.message = $filter('translate')('MESSAGE_KEY', {someParam: '<test>'}, 'messageformat');
    }]);
    <!doctype html>
    <html ng-app="AsdDTestApp">
    
    <head>
      <script src="https://cdnjs.cloudflare.com/ajax/libs/angular.js/1.5.5/angular.js"></script>
      <script src="https://cdn.rawgit.com/angular-translate/bower-angular-translate/2.17.0/angular-translate.js"></script>
    </head>
    
    <body>
      <div ng-controller="Ctrl as vm">
        Here is my input box:
          <input type="textarea" ng-model="vm.message">
      </div>
    </body>
    </html>

    You need tot use

    $translateProvider.useSanitizeValueStrategy('sceParameters');
    

    instead of

    $translateProvider.useSanitizeValueStrategy('escapeParameters', 'sanitizeParameters');
    

    sanitize: sanitizes HTML in the translation text using $sanitize

    escape: escapes HTML in the translation

    sanitizeParameters: sanitizes HTML in the values of the interpolation parameters using $sanitize

    escapeParameters: escapes HTML in the values of the interpolation parameters

    sce: wraps HTML in $sce.trustAsHtml(value)

    sceParameters: wraps HTML in the values of the interpolation parameters in $sce.trustAsHtml(value)

    more on escaping variables in angular translate