Reputation: 13
I have an Angularjs script to create a navigation Bar using users parameters. The problem is that, when i try to render the html structure, it always displays as plain text
This is the script:
var app = angular.module('userData', []);
app.controller('showUserData', ['$scope', function($scope){
$scope.userPar = JSON.parse(sessionStorage.userPar);
$scope.navBar = createNavBar($scope.userPar);
$scope.logOut = function(){
alert('Out you go!');
}
}]);
app.directive("otcNavbar", function(){
return {
template:"{{navBar}}"
};
});
function createNavBar(userPar){
var navBar = "<ul id=\"nav\">";
if(userPar.isDir == 1){
navBar +=
"<li class=\"seccion\"><a href=\"#\">Director</a></li>";
}
if(userPar.isSys == 1){
navBar +=
"<li class=\"seccion\"><a href=\"#\">System</a></li>";
}
navBar +=
"<li class=\"seccion\"><a href=\"\" ng-click=\"logOut()\">Log Out</a></li></ul>";
return navBar;
}
This is the template:
<html>
<head>
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<link id="css" rel="stylesheet" href="main.css" type="text/css" />
<script src="angular.min.js"></script>
<script src="mainApp.js"></script>
</head>
<body>
<div id="userPar" ng-app="userData" ng-controller="showUserData">
<table id="sessionData">'.
<tr><th colspan="6">User Data</th></tr>'.
<tr><td class="R B">User No.:</td><td class="L">{{userPar.suID}}</td>.
<td class="R B">Name:</td><td class="L">{{userPar.sulName}}, {{userPar.sufName}}</td>.
<td class="R B">Access:</td><td class="L">{{userPar.utName}}</td></tr>
</table>
<!--<div id="navBar" otc-navbar></div>-->
<div id="navBar" ng-bind="navBar"></div>
</div>
</body>
</html>
I tried a directive (otc-navbar) and ng-bind, but in both cases i get plain text instead of html. How can I make it work? Thanks in advance!
Upvotes: 1
Views: 924
Reputation: 218892
Use ng-bind-html
with angular sanitize
<div id="navBar" ng-bind-html="navBar"></div>
ng-bind-html will evaluates your expression and inserts the resulting HTML into the element. By default, the resulting HTML content will be sanitized using the $sanitize
service. In order to use ngSanitize
, you need to include "angular-sanitize.js
" in your application.
So include angular-sanitize.js
in your page and inject the dependency to your angular module.
var app= angular.module('userData', ['ngSanitize']);
Here is a working sample on jsbin. :)
EDIT : As per the comment you wish ng-sanitize to not strip out the html attributes.
By default, ng-sanitize
strips certain attributes out. If you really want that to not happen, You can use the $sce service's trustAsHtml
method to explicitly tell angular that the markup you are passing is safe.
Here is a working sample
Upvotes: 1