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

1 comment:

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

    ReplyDelete

Blogroll

Follow this blog by Email

Popular Posts