Bhushan Khaladkar
Bhushan Khaladkar

Reputation: 622

ng-bind-html values to other html tags

I want to take data from ng-bind-html and bind it to some other html tags.Though i can directly use ng-bind-html for it. But is there any other way where we can use the binded html to other HTML tags?

JS:

 $scope.left = '<span>Hello World</span><strong>New Testing<strong><br/>h1>Testing</h1>';

HTML:

<div ng-bind-html="left" ng-model="GetValues"></div>

<span>{{GetValues}}</span>

Upvotes: 0

Views: 3436

Answers (2)

Ramesh Rajendran
Ramesh Rajendran

Reputation: 38693

Way 1 : Achieve with using $compile

html

<div my-directive="left" ng-model="GetValues"></div>

directive

var app = angular.module('myApp',[]);
app.controller('ctrlMain',function($scope){
    $scope.bindMe = {id:1,myvar:"test"};
});
app.directive('myDirective', function($compile){
  return{
    restrict: 'A',
    scope: {
        varToBind: '=myDirective'     
    },
    link: function(scope, elm, attrs){
      outerList = '<span>Hello World</span><strong>New Testing<strong><br/>h1>Testing</h1>';
      outerList = $compile(outerList)(scope);
      elm.replaceWith(outerList);
    }
  }
});

way 2: Achieve with using AngularJS ng-include

you can directly include a html file :)

<div ng-include="'myFile.htm'"></div>//your DOM string code should be in myfile.htm file

Upvotes: 1

Sachila Ranawaka
Sachila Ranawaka

Reputation: 41445

use trustAsHtml to compile the string into Dom

$scope.trustAsHtml = function(html){
   return $sce.trustAsHtml(html);
}

now call the function in the html

<div ng-bind-html="trustAsHtml(left)" ng-model="GetValues"></div>

angular.module("app",[])
.controller("ctrl",function($scope,$sce){
 $scope.left = '<span>Hello World</span><strong>New Testing<strong><br/><h1>Testing</h1>';

  $scope.trustAsHtml = function(html){
    return $sce.trustAsHtml(html);
  }
})
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<div ng-app="app" ng-controller="ctrl">
  <div ng-bind-html="trustAsHtml(left)" ng-model="GetValues"></div>

<span>{{GetValues}}</span>
</div>

Upvotes: 0

Related Questions