Andrei Andrei - 1 month ago 12
AngularJS Question

Ionic / Angular, pass JSON/Array value as HTML

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:

enter image description here

How can I fix this? (Sorry if it's a noob question, I am just getting started with Angular)

Answer

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);
                });
            }
        };
    };
})();
Comments