Sachila Ranawaka
Sachila Ranawaka

Reputation: 41445

angular bind html tags from controller to html view

I need to render the $scope.htmlView tags in to html view.

I already tried using ng-bind-html. It renders the html tags but scope variable values will not appear.

How can I render both html tags and and scope variable values?

This is the controller:

$scope.newObj = {
  billStatus : true;
  eventTime : "2015-01-10"
};

$scope.htmlView = '<p>{{newObj.eventTime}}</p>    <div style="margin-top: -15px;"><md-checkbox ng-checked="{{newObj.billStatus}}" style="margin-left: 0px;" aria-label="Bilable"><span style="margin-left:0px;">Bilable</span> </md-checkbox></div>'

Expected result is:

<p> 2015-01-10</p> 
<div style="margin-top: -15px;">
  <md-checkbox ng-checked="true" style="margin-left: 0px;" aria- label="Bilable">
    <span style="margin-left:0px;">Bilable</span>
  </md-checkbox>
</div>

I search over the internet over days and still could't find out a way to figure out this. please help me. thank you.

Upvotes: 0

Views: 1368

Answers (3)

Gayathri Mohan
Gayathri Mohan

Reputation: 2962

Hi please check this fiddle https://plnkr.co/edit/iqNltdDYv2n9Agke0C2C?p=preview

HTML

  <div ng-controller="ExampleController">
      <p >{{newObj.eventTime}}</p>
       <p dynamic="htmlView"></p>
</div

and JS

(function(angular) {
  'use strict';
angular.module('bindHtmlExample', ['ngSanitize'])
  .controller('ExampleController', ['$scope', function($scope) {

       $scope.newObj = {
      billStatus : true,
      eventTime : "2015-01-10"
}

$scope.htmlView = '<p> {{newObj.eventTime}}</p> <div style="margin-top: -15px;">Hello <md-checkbox ng-checked="{{newObj.billStatus}}" style="margin-left: 0px;" aria-label="Bilable"><span style="margin-left:0px;">Bilable</span> </md-checkbox></div>'
  }])

  .directive('dynamic', function($compile) {
    return {
        restrict: 'A',
        replace: true,
        link: function (scope, element, attrs) {
            scope.$watch(attrs.dynamic, function(html) {
                element[0].innerHTML = html;
                $compile(element.contents())(scope);
            });
        }
    };
});
})(window.angular);

Upvotes: 0

Vivek Singh
Vivek Singh

Reputation: 169

I will tell you a long way but it will help you.Make a custom directive like this.

app.directive('dynamic', function ($compile) {
return {
restrict: 'A',
replace: true,
link: function (scope, ele, attrs) {
  scope.$watch(attrs.dynamic, function(html) {
    ele.html(html);
    $compile(ele.contents())(scope);
  });
  }
   };
  });

Use as

<span  dynamic="{{htmlView}}" > 

Upvotes: 0

Drag13
Drag13

Reputation: 5998

You have to do 2 things.

  1. Use data-ng-bind-html=""
  2. Use $sce.trustAsHtml(string)

UPDATED: If you wont to use angular expressions, you have to compile them using

$compile.

You can read more via this $SCE

Upvotes: 1

Related Questions