Reputation: 10062
I have a mysql database that stores a text value (a body of an article), that I want to display on my page. I would like to store and then display some text formatting but don't know how to do it with angular.
I use the php PDO echo json_encode
to output my database query results.
So I figured I'd just insert some html markup into my text (some heading and paragraph tags), and let the browser format it, but now my browser shows the html markups as text.
Is there an AngularJS filter to do this easily? I searched trough the documentation but was unable to find anything like it.
I don't really want to write html markups for every single article I inted to store inside the database, but I have no idea how else to do it. Before, I just wrote a custom jQuery function that replaced line brakes with <br>
and so on.
Here's my code:
html:
<div id="full-article" ng-repeat="fArticle in fullArticle" ng-show="!feed" ng-hide="feed">
<h1>{{ fArticle.title }}</h1>
<h3>{{ fArticle.posted | date:"dd.MM.yyyy"}}</h3>
<p>{{ fArticle.body }}</p>
<button ng-click="backToFeed()">Back to articles</button>
</div>
controller:
'use strict';
angular.module('ptcAngularJsApp')
.controller('ArticlesCtrl', function ($scope, $http) {
//
$scope.fullArticle = [];
$scope.feed = true;
$scope.message = '';
$scope.findArticleByTitle = function(article) {
$http.post('http://localhost/PTC_db_PHP/article_by_title.php', article.title).
success(function(response) {
$scope.fullArticle = response;
$scope.feed = false;
}). //end http post response
error(function(err) {
console.log(err);
}); //end http post error
}; //end findArticleByTitle
}); //end .controller
I removed the parts of my code irrelevant to this question. If you need more
Upvotes: 4
Views: 3958
Reputation: 28750
Angular doesn't allow you to display html right away, you have to say that it's trusted so change your success to this (make sure you have dependency injected $sce):
$scope.fullArticle = response;
for(var x = 0; x < $scope.fullArtcile.length; x++){
$scope.fullArticle[x].trustedBody = $sce.trustAsHtml($scope.fullArticle[x].body)
}
And then make your html this:
<p data-ng-bind-html="fArticle.trustedBody"></p>
You can read up on it here: https://docs.angularjs.org/api/ng/directive/ngBindHtml and also look at the following answer: With ng-bind-html-unsafe removed, how do I inject HTML?
Upvotes: 1
Reputation: 4654
What you need is ngBindHtml. Check it out here: https://docs.angularjs.org/api/ng/directive/ngBindHtml
Upvotes: 0