2

I'm taking a HTML content to the front end javascript code, from the database which was saved as varchar. It is stored in a variable called vm.htmlContent And then I want to display this string type HTML content again as HTML in my web page. I use ng-bind-html angular directive for doing this. My HTML content which is stored in vm.htmlContent variable is:

<p> Date: </ p> <p> Time: </ p> <p> Venue: </ p>

The current javascript code for this is looks like:

<ng-bind-html
    ng bind-html="vm.htmlContent">
 </ng-bind-html>

the output in the web page is:

Date:
Time:
Venue:

I want to add Date,Time and venue from other angular variables inside this ng-bind-html. The date,time and venue variables are vm.date,vm.time and vm.venue and they keep the relevant data clearly. Is there a way to do this without spiting the string content in vm.htmlContent variable?

Ramesh Rajendran
  • 37,412
  • 45
  • 153
  • 234
  • Is using the `htmlContent` variable even necessary here? Unless I'm missing something, seems like you could render the other three variables with the "Date:", "Time:", etc. text yourself – kingdaro Mar 07 '18 at 06:16
  • The html content is taking from the database and it is stored in `vm.htmlContent` variable. I can't just type the text by myself in the javascript code. It has to be come from the database and for storing it I use `vm.htmlContent` variable. So that is the usage of it –  Mar 07 '18 at 06:31

2 Answers2

0

A few .replace() calls would be a fairly straight-forward way of getting those variables in there:

vm.getReplacedContent = () => {
  return vm.htmlContent
    .replace('Date:', `Date: ${vm.date}`)
    .replace('Time:', `Time: ${vm.time}`)
    .replace('Venue:', `Venue: ${vm.venue}`)
}

<div ng-bind-html="vm.getReplacedContent()"></div>

Though I'm not experienced with angular, and I'm not sure if the HTML will automatically update doing things this way. If it doesn't update, instead of a function, you might have to use another scope variable and $watch the vm.htmlContent variable to update it.

kingdaro
  • 11,528
  • 3
  • 34
  • 38
0

Try this way by using replace

    
    
  angular.module("myApp", []).controller("myCtrl", function($scope,$sce) {
  $scope.date="03/07/2018";
  $scope.time="1.00 PM";
  $scope.venue="US"
  $scope.myTexts = "<p> Date: </ p> <p> Time: </ p> <p> Venue: </ p>";
  var replacedData =  $scope.myTexts.replace("Date:","Date:" + $scope.date).replace("Time:","Time:" + $scope.time).replace("Venue:","Venue: " + $scope.venue);
  $scope.myText = $sce.trustAsHtml(replacedData);      
    });
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.6.4/angular.min.js"></script>
 <div ng-app="myApp" ng-controller="myCtrl">    
        <p ng-bind-html="myText"></p>    
 </div>
Ramesh Rajendran
  • 37,412
  • 45
  • 153
  • 234