Issue with ng-bind-html - html

I'm trying to create a website using angular-js .I'm using rest api calls for getting data. I'm using ngSanitize as the data from rest call includes html character. Even if i use ng-bind-html in my view the html tags are not removed .What is the mistake in my code.Can anyone help me
var app = angular.module('app',['ngSanitize','ui.bootstrap']);
app.controller("ctrl",['$scope','$http','$location','$uibModal',function($scope,$http,$location,$uibModal,){
//here im making my rest api call and saving the data in to $scope.items;
}]);
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.5.6/angular.min.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.5.6/angular-sanitize.js"></script>
<body ng-app="app" ng-controller="ctrl">
<div class="hov" ng-repeat ="item in items">
<br/>
<div>
<hr class="divider" style="overflow:auto;">
<ul>
<li style="font-family: Arial, Helvetica, sans-serif;font-weight:900px;">
<h3>Name<span style="color:#0899CC;" ng-model="id2" ng-bind-html="item.name"></span></h3>
</li>
<li>
<h4>Description: <span ng-bind-html="item.description"></span></h4>
</li>
</ul>
</div>
</div>
</body>

So you want to allow HTML tags or deny them ?
If you want the html to be escaped in the data coming from your server, just use ng-bind. It will replace < with < and > with > thus showing the HTML tags instead of computing them.
If you want to completely remove any HTML tags
Try this filter
filter('htmlToPlaintext', function() {
return function(text) {
return text ? String(text).replace(/<[^>]+>/gm, '') : '';
};
}
);
then in your HTML :
<h3>Name<span style="color:#0899CC;" ng-model="id2" ng-bind-html="item.name | htmlToPlaintext"></span></h3>
If you trust the source and want to compute the HTML it send you
You can use this filter
app.filter('trusted', function($sce){
return function(html){
return $sce.trustAsHtml(html)
}
});
then in your HTML :
<h3>Name<span style="color:#0899CC;" ng-model="id2" ng-bind-html="item.name | trusted"></span></h3>
And
<h4>Description: <span ng-bind-html="item.description | trusted"></span></h4>

I have the same problem before some time , then i created a filter for this problem, You can use this filter to do sanitize your html code:
app.filter("sanitize", ['$sce', function($sce) {
return function(htmlCode) {
return $sce.trustAsHtml(htmlCode);
}
}]);
in html you can use like this:
<div ng-bind-html="businesses.oldTimings | sanitize"></div>
businesses.oldTimings is $scope variable having description of strings or having strings with html tags , $scope.businesses.oldTimings is the part of particular controller that you are using for that html.
see in the snapshot:
you can use limitHtml filter to do the same:
app.filter('limitHtml', function() {
return function(text, limit) {
var changedString = String(text).replace(/<[^>]+>/gm, ' ');
var length = changedString.length;
return changedString.length > limit ? changedString.substr(0, limit - 1) : changedString;
}
});
Then you can add bothe filter in your html like that:
<p class="first-free-para" ng-bind-html="special.description| limitHtml : special.description.length | sanitize">
Hope it will work for you.

Related

How can I use ng-bind-html inside my directive?

I'm using templates based on my JSON. So, I can't really use my ng-bind-html like I would normally do.
Seems like the only option I have is to use my sanitized html inside an directive.
Looking for similar questions, I couldn't figure it out how to apply in my case.
Yes, I am pretty newbie into angular.
I'm currently receiving this data from my controller:
$scope.safecontainers = $sanitize($scope.containersmsg);
In my html would normally be like this:
<p ng-bind-html="containersmsg"></p>
But I don't want this, I need to use this ng-bind-html inside a directive!
Some people have talked about $compile, but I couldn't really figure it out how to apply in my case.
EDIT:
Based on comments, i'll add more code to help you guys further understand my goal.
Inside my index.html I'm declaring the controllers needed and calling my
<ng-view></ng-view>
Then, based on what I receive, i'll load one view or another:
<div ng-if='setores[0].SetorTema == "1"'>
<theme-one titulo="{{setores[0].SetorNome}}" logo="
{{setores[0].SetorLogo}}" evento="{{evento[0].EventoNome}}">
</theme-one>
// I omitted some of the parameters because they ain't relevant
</div>
My template is like this: (Just a little part of it to avoid much useless code)
<section class="target">
<div class="col-md-6 col-xs-12">
<div class="" ng-repeat="banner in title">
<div class="target-title">{{ banner.BannerLevelTitulo }}
</div>
<div class="target-desc">{{banner.BannerLevelDescricao}}</div>
</div>
</div>
<div class="col-md-6 col-xs-hidden">
<div class="target-image"><img ng-src="{{targetimage}}" alt="">
</div>
</div>
</section>
This is the controller I want my sanitized code.
hotsite.controller('containerController', function($scope, $http, $sanitize)
{
$scope.containers = [];
$scope.containersmsg = '';
$scope.safecontainers = $sanitize($scope.containersmsg);
$http.get('/Admin/rest/getContainer')
.then(function onSuccess(response) {
var data = response.data;
$scope.containers = data;
$scope.containers = response.data.filter(containers =>
containers.ContainerAtivo);
$scope.containersmsg = $scope.containers[0].ContainerDesc;
})
.catch(function onError(response) {
var data = response.data;
console.log(data);
});
});
This is a piece of my directive:
angular.module('hotsiteDirectives', [])
.directive('themeOne', function($compile) {
var ddo = {};
ddo.restrict = "AE";
ddo.transclude = true;
ddo.scope = {
titulo: '#',
...
(a lot of other scope's)
contimg: '#'
};
ddo.templateUrl = 'app/directives/theme-one.html';
return ddo;
})
And yes, I am calling the ngSanitize
var hotsite = angular.module('hotsite',['ngRoute', 'hotsiteDirectives',
'ngSanitize']);
TL;DR
This is how my code looks like inside a directive, with raw html and not rendered:
This is how it works with ng-bind-html, formatted html
If I do put this inside my view
<p ng-bind-html="containersmsg"></p>
It will be alright, all of it working like it should.
BUT, I need to call this only inside my directive, and I don't know how to do it.
So, with this context:
How can I put my sanitized html inside my directive and template?
You don't even have to trust the html to render it using ngBindHtml because the directive already does it for you. You basically need to create a parameter attribute for your directive to hold the html string, so, inside the directive's template, you use ng-bind-html="myParam".
The following snippet implements a simple demonstration of creating a directive that receives and renders an html input parameter that comes from a controller.
angular.module('app', ['ngSanitize'])
.controller('AppCtrl', function($scope) {
$scope.myHtml = '<div><b>Hello!</b> I\'m an <i>html string</i> being rendered dynamicalli by <code>ngBindHtml</code></div>';
})
.directive('myDirective', function() {
return {
template: '<hr><div ng-bind-html="html"></div><hr>',
scope: {
html: '='
}
};
});
<div ng-app="app" ng-controller="AppCtrl">
<my-directive html="myHtml"></my-directive>
</div>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.6.0/angular.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.6.0/angular-sanitize.js"></script>

How to Display value of dynamically created varible using AngularJS

My HTML template code is:
<p>{{"fieldname_"+lang}}</p>
In the controller I have the following:
$scope.lang = "mr";
$scope.fieldname_mr = "Dynamic varible";
I want the result to be Dynamic varible, but it is fieldname_mr.
How can I achieve that?
You can use bracket notation to achieve this:
angular.module('app', [])
.controller('testController',
function testController($scope) {
$scope.lang = "mr";
$scope.dynamicVars = {fieldname_mr : "Dynamic varible"};
});
<body ng-app="app">
<div class="table-responsive" ng-controller="testController">
{{dynamicVars["fieldname_" + lang]}}
</div>
</body>
<script src="//ajax.googleapis.com/ajax/libs/angularjs/1.6.4/angular.min.js"></script>
that you wnt is not able, i made a middleware solution that mantains all your needed but passed by a function that made the return of var, understand that angular force to made like this
<div ng-controller="MyCtrl">
<span ng-init="">{{getValue('fieldname_'+lang)}}</span>
</div>
var myApp = angular.module('myApp',[]);
function MyCtrl($scope) {
$scope.lang = "mr"; $scope.fieldname_mr = "Dynamic varible";
$scope.getValue =function(name){
return $scope[name] ||'no existe man';
}
}
Yes you can do it like you set your dynamic variable in angular as follow:
what you want variable name store in variable than follow code:
$scope[dynamic_var]=Value of variable;
when you fetch this value as like:
Use this when you not fix property of scope
alert($scope[dynamic_var])
use when you have fix property name
alert($scope.dynamic_var)

html entities decode angular

I am trying to decode html entities in Angular, and seen some solutions for some strings with Sanitize, but I have a lot of JSON documents in my db with that I need sanitized. How can I do this? Right now my html shows the full
<h2>Badkamer</h2>
inclusive the tags.
This is a part of my json document
{
"badkamer" : {
"content" : "<h2>Badkamer</h2>"
<p>text</p>
}
}
This is my angular controller
app.controller('DataCtrl', ['$sce', function($scope,$http,$sce){
$scope.specials = function(){
$scope.special = [];
$http.get('/specialdata').then(function(d){
$scope.special = d.data[0];
console.log(d.data);
},function(err){
console.log(err);
});
};
}]);
This is the page where I show my data from MongoDB
<div class="align-content-inner">
<div>
{{special.badkamer.content}}
</div>
</div>
You need to include angular-sanitize.js script in HTML, and ngSanitize module on your app.,
Like :
var app = angular.module('myApp', ['ngSanitize']);
and use ng-bind-html directive.., like:
<div ng-bind-html="special.badkamer.content"></div>
See this demo plunker.

ng-bind-html not working with my $scope.variable

I am trying to add something like dynamic HTML using ng-bind-html but its not working with $scope variable
Here is my Angular code
1)My controller
$scope.name = "Parshuram"
$scope.thisCanBeusedInsideNgBindHtml = $sce.trustAsHtml("<div>{{name}}</div>");
Also that my string is dynamic
"<div><table class=" + "\"table table - bordered table - responsive table - hover add - lineheight table_scroll\"" + "><thead><tr><td>Name</td><td>Age</td></tr></thead><tbody><tr ng-repeat=" + "\"tr in dyna\"" + "><td>{{tr.name}}</td><td>{{tr.age}}</td></tr></tbody></table></div>"
So i cant replace every variable with $scope
2)- My HTML
<div ng-app="mymodule" ng-controller="myModuleController">
<div ng-bind-html="thisCanBeusedInsideNgBindHtml"></div>
</div>
I got this output
{{name}}
My expected output is
Parshuram
Please can anyone help i am stuck at this point,does that $sce does not bind scope variable?? ..
I've created a working plnkr here: https://plnkr.co/edit/uOdbHjv1B7fr0Ra1kXI3?p=preview
the problem is that ng-bind-html is not bound to the scope.
you should manually compile the content.
a valid and reusable solution should be creating a directive, whitout using any external modules.
function compileTemplate($compile, $parse){
return {
link: function(scope, element, attr){
var parsed = $parse(attr.ngBindHtml);
function getStringValue() { return (parsed(scope) || '').toString(); }
scope.$watch(getStringValue, function() {
$compile(element, null, -9999)(scope);
});
}
}
}
<div ng-app="mymodule" ng-controller="myModuleController">
<div ng-bind-html="thisCanBeusedInsideNgBindHtml" compile-template></div>
</div>
ng-bind-html does what it says on the tin: it binds html. It doesn't bind angular template code into your dom.
You need to do this instead:
$scope.thisCanBeusedInsideNgBindHtml =
$sce.trustAsHtml("<div>"+$sanitize(name)+"</div>");
To do this you'll want to include the module ngSanitize from the javascript angular-sanitize.js. See https://docs.angularjs.org/api/ngSanitize
If you want to insert some html that includes angular directives then you should write your own custom directive to do it.
In your html just use
{{name}}
The {{var}} notation is to be used in the HTML code to evaluate that variable.
You can do :
$scope.thisCanBeusedInsideNgBindHtml = $sce.trustAsHtml('<div ng-bind="name"></div>');
Sorry I make another answer.
If you have
$scope.thisCanBeusedInsideNgBindHtml = $sce.trustAsHtml("<div>{{name}}</div>");
Then you can do
var str = "<div>{{name}}</div>";
var output = str.replace('{{name}}', $scope.name);
It seems to be the only option.

AngularJS - Sharing Data between controllers from json

actually I get stucked since several days with following problem. I like to create a small app which loads data from a json file. The app should consist of 3 views !
Show a list of data
Edit view for changing current data
add view to store new data
Now I learned to use a service which provides data to each controller for each view.
But for the time my service works only with generated data within my variable thing.
How Can I change this that my service will provide data from .json file which may be edited and updated with any controller !
Thanks
Here is my code and plnker
<!doctype html>
<html ng-app="project">
<head>
<title>Angular: Service example</title>
<script src="http://code.angularjs.org/angular-1.0.1.js"></script>
<script>
var projectModule = angular.module('project',[]);
projectModule.factory('theService', function() {
return {
thing : [{"DATE" : "2014","IATA":"DUS","DUTY":"10:12"},
{"DATE" : "2015","IATA":"MIA","DUTY":"10:12"},
{"DATE" : "2017","IATA":"JFK","DUTY":"10:12"}]
};
/*
return {
thing:[function($http) {
return $http.get('data.json').then(function(response) {})
return response.data;
}]
};
*/
});
function FirstCtrl($scope, theService) {
$scope.thing = theService.thing;
$scope.name = "First Controller";
}
function SecondCtrl($scope, theService) {
$scope.someThing = theService.thing;
$scope.name = "Second Controller!";
}
</script>
</head>
<body>
<div ng-controller="FirstCtrl">
<h2>{{name}}</h2>
<div ng-repeat="show in thing">
<p>
<b>DATE </b>{{show.DATE}}
<b>IATA </b>{{show.IATA}}
<b>DUTY </b>{{show.DUTY}}
</p>
</div>
<div ng-controller="SecondCtrl">
<h2>{{name}}</h2>
<div ng-repeat="edit in someThing">
<p>
<input ng-model="edit.DATE"/>
<input ng-model="edit.IATA"/>
<input ng-model="edit.DUTY"/>
</p>
</div>
</div>
</body>
</html>
All you have to do is use $http service and return it:
getJson: function() {
return $http.get('data.json')
}
Then in your controller you use it like this:
service.getJson(function(data) {
$scope.thing = data;
})
To convert object to json you need to use angular.fromJson i angular.toJson
Angular Docs
After that you do:
$http.post('yourjson);
to replace your current json (save changes).
You should also redownload it (to have everything in sync) using $http.get as I described above.
I have found an example example. I hope it helps.