0

My database has this html string stored:

string myVar = "<p><custom-dir item='myItem' /> and some other random text </p>";

This is then used in text-angular block on the front end, which is editable, something like this:

<text-angular placeholder="Something" ng-model="myVar" />

Now I have a template for customDir which looks like this:

<span class="custom-class" contenteditable="false">{{myItem.text}}</span>

When displayed, however, the template for customDir is not used, which means the text-angular block has nothing where there should be {{myItem.text}}. How can I solve this issue?

Günter Zöchbauer
  • 623,577
  • 216
  • 2,003
  • 1,567

1 Answers1

0

You can compile a string into a template by using the $compile service. The template can be then used to procude a DOM element. Then you can insert it where you want.

Example:

// Get the template
// Note that AngularJS does not support auto closed tag. So you have to write <custom-dir item='myItem'></custom-dir> and not <custom-dir item='myItem'/>
var template = $compile("<p><custom-dir item='myItem'></custom-dir> and some other random text </p>");
// Get the DOM element
var node = template(scope); // This can be a directive scope or a controller scope. But a template need a scope to be executed.
// Insert the DOM element
angular.element(document.getElementById('my-container')).append(node);

Working code snippet:

angular.module('app', [])

.directive('testDir', function($compile) {
  return {
    restrict: 'E',
    scope: {},
    link: function(scope, element) {
      var template = $compile('<p><custom-dir item="hello world"></custom-dir></p>');
      var node = template(scope);
      element.append(node);
    }
  };
})

.directive('customDir', function() {
  return {
    restrict: 'E',
    scope: {
      item: '@'
    },
    template: '<span>{{ item }}</span>'
  };
});
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.5.6/angular.min.js"></script>

<div ng-app="app">
  <test-dir></test-dir>
</div>
Magus
  • 14,796
  • 3
  • 36
  • 51
  • I tried this method already. The variable node you mentioned still shows as instead of {{myItem.text}}. Am I doing something wrong? – Aditya Srivastava Feb 22 '18 at 08:44
  • Yes you are doing something wrong. AngularJS does not support auto closed tags. Try to replace with `` – Magus Feb 22 '18 at 08:46
  • I added a code snippet with a working example of using `$compile`. It can't do more than that sorry. – Magus Feb 22 '18 at 09:08
  • Oh ok, I know why we are having different results. I don't display the compiled result immediately. I need to store the compiled result in the myVar string. Basically `myVar = "

    and some other random text

    "` should change to `myVar = "

    {{myItem.text}} and some other random text

    ";`
    – Aditya Srivastava Feb 22 '18 at 09:14