Inject Html In AngularJs Using $sce And ng-bind-html
19:32Introduction
In this article I show how to inject html in view page using "$sce" and "ng-bind-html".Browser View Image
Using Js & CSS
<link href="~/css/font-awesome.min.css" rel="stylesheet" /> Download <script src="~/js/angular.js"></script> Download
Controller
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
namespace AngularHtmlInject.Controllers
{
public class TestController : Controller
{
public ActionResult Index()
{
return View();
}
}
}
app.js
var app = angular.module('myApp', []);
app.controller('myController', function ($scope, $sce) {
$scope.HoverIn = function () {
var html = '<p class=tooltip>Thank You For Hover Me!</p>';
this.varHtml = $sce.trustAsHtml(html);
this.isHover = true;
};
$scope.HoverOut = function () {
this.isHover = false;
};
});
View
@{
Layout = null;
}
<!DOCTYPE html>
<html>
<head>
<meta name="viewport" content="width=device-width" />
<title>Html Inject In AngularJs</title>
<link href="~/css/font-awesome.min.css" rel="stylesheet" />
<script src="~/js/angular.js"></script>
<script src="~/js/app.js"></script>
<style>
.tooltip {
width: 210px;
background: #0193cf;
color: #fff;
position: relative;
top: -13px;
left: 0px;
z-index: 9999;
padding: 10px 5px;
border-radius: 13px;
font-weight:bold;
}
.tooltip:before {
content: "\f0d8";
font-family: FontAwesome;
position: absolute;
top: -15px;
left: 19px;
color: #0193cf;
font-size: 22px;
}
.main {
width:20%;
height:100px;
margin-left:35%;
background-color:#eeeeef;
margin-top:10%;
padding:100px;
}
.text {
color:blue;
font-size:20px;
font-weight:bold;
cursor:pointer;
}
</style>
</head>
<body ng-app="myApp">
<div class="main" ng-controller="myController">
<h1>Html Inject In AngularJs</h1>
<div class="text" ng-mouseover="HoverIn()" ng-mouseleave="HoverOut()">Mouse Over Me</div>
<div ng-show="isHover" ng-bind-html="varHtml"></div>
</div>
</body>
</html>


0 comments