AngularJS supports .html(), .text() jQuery functionality. Here in below examples we can see how to set text or html to an element.

Steps to set text to an elemnt :

  1. Get angular element of html element
  2. Use .text() method to set text to that angular element
var myEl = angular.element( document.querySelector( '#divID' ) );
myEl.text('This is text. Here html tags will be displayed like normal tags. Example : <span style="font-weight:bold;"> Styled Text</span>');     

Set Text using ng-bind

ng-bind is for binding text to HTML element
<html ng-app="" ng-controller="myCtrl">
.....
<script src="//ajax.googleapis.com/ajax/libs/angularjs/1.2.15/angular.min.js"></script>
.....
<input ng-model="divText"/>
.....
<div style="border:1px solid #ccc;padding:10px;" ng-bind="divText"></div>
<script>
function myCtrl($scope) {
  $scope.divText = 'some text';
}
</script>
Try It Your Self

Steps to set html to an element :

  1. Get angular element
  2. Use .html() method to set html to that angular element
var myEl = angular.element( document.querySelector( '#divID' ) );
myEl.html('This is html. Here html tags will be mixed with page. Example : <span style="font-weight:bold;"> Styled Text</span>');     

Set HTML using ng-bind-html

ng-bind-html is for binding HTML to element
<html ng-app="myApp" ng-controller="myCtrl">
.....
<script src="//ajax.googleapis.com/ajax/libs/angularjs/1.2.15/angular.min.js"></script>
<script src="//ajax.googleapis.com/ajax/libs/angularjs/1.4.3/angular-sanitize.js"></script>
.....
Enter some text in below text field <br/>
<input ng-model="divHtmlVar"/><br/><br/>
<div style="border:1px solid #ccc;padding:10px;" ng-bind-html="divHtmlVar"></div>
<script>
var myApp = angular.module('myApp', ['ngSanitize'])
function myCtrl($scope) {
    $scope.divHtmlVar = '<b>main html</b>';
}
</script>
Try It Your Self

3 comments:

  1. Good Example to Set Text or Html to div using AngularJS, i am interesting to learn AngularJs 4, give me more examples

    ReplyDelete
  2. The great service in this blog and the nice technology is visible in this blog. I am really very happy for the nice approach is visible in this blog and thank you very much for using the nice technology in this blog
    Angularjs course in chennai

    ReplyDelete
  3. Hi, great to see your website. I like the content and the research done behind every aspect of your blog. It looks great and very knowledgeable. Keep it up the good work. PCNSE questions answers

    ReplyDelete

Blogroll

Follow this blog by Email

Popular Posts