Reputation: 3162
I am building a Mobile App using Ionic Framework and Angular. I have this array in my services JS (for this demo, only one value is passed):
// Some fake testing data
var articles = [{
id: 0,
title: 'This is the title',
intro: 'This is the intro.',
image: 'img/ben.png',
published: '31/10/2016',
text: '<p>Lorem ipsum dolor sit amet, consectetur adipiscing elit. Integer urna lacus, aliquam sed ante vitae, ornare fermentum ipsum. Duis pellentesque.</p><p>Lorem ipsum dolor sit amet, consectetur adipiscing elit. Integer urna lacus, aliquam sed ante vitae, ornare fermentum ipsum. Duis pellentesque.</p>',
url: 'http://www.domain.com/article'
}];
And this is how my controllers JS looks like for this specific page:
.controller('NewsDetailCtrl', function($scope, $stateParams, Articles) {
$scope.article = Articles.get($stateParams.articleId);
})
The HTML template looks like this:
<ion-view view-title="Article">
<ion-content class="padding">
<img ng-src="{{article.image}}" style="width: 64px; height: 64px">
<p>
{{article.text}}
</p>
</ion-content>
</ion-view>
Now, in the App, {{article.text}}
is passed as it is, not as HTML. You can have a look at the image below:
How can I fix this? (Sorry if it's a noob question, I am just getting started with Angular)
Upvotes: 0
Views: 277
Reputation: 173
Use ng-BindHtml instead of ng-model. Content of ng-model is sanitized.
Please see examples on https://docs.angularjs.org/api/ng/directive/ngBindHtml
Alternatively you can use $sce.trustAsHtml():
$scope.html = '<p>html content</p>';
$scope.trustedHtml = $sce.trustAsHtml($scope.html);
For more see: https://docs.angularjs.org/api/ng/service/$sce
Upvotes: 1
Reputation: 1260
Either you can use
$scope.text= $sce.trustAsHtml(articles.text);
<p ng-bind-html="text"></p>
or write a directive like this,
(function() {
'use strict';
angular
.module('app')
.directive('dynamic', dynamic);
dynamic.$inject = ['$compile'];
function dynamic($compile) {
return {
restrict: 'A',
replace: true,
link: function (scope, ele, attrs) {
scope.$watch(attrs.dynamic, function(html) {
ele.html(html);
$compile(ele.contents())(scope);
});
}
};
};
})();
Upvotes: 1
Reputation: 1696
You need to use $sce service for this .. refer this
https://docs.angularjs.org/api/ng/service/$sce
$scope.text= $sce.trustAsHtml(articles.text);
And in your controller use it like this, Make sure you have injected $sce in your controller before using it
<p ng-bind-html="text"></p>
Thanks
Upvotes: 0