Formatting text with AngularJS

I have a mysql database that stores a text value (article body) that I want to display on my page. I would like to save and then display some text formatting, but don't know how to do it with angular.

I am using php PDO echo json_encodeto output the results of a database query.

So, I decided that just paste some HTML markup into your text (some title and paragraph tags) and let the browser format it, but now my browser shows the html markup as text.

Is there an AngularJS filter to make this easy? I was looking for documentation, but could not find anything like it.

I don’t want to write html markup for every single article that I would like to store inside the database, but I have no idea how to do this. I used to just write a custom jQuery function that replaced linear brakes with <br>, etc.

Here is 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 have removed parts of my code that are not relevant to this issue. If you need more

+4
source share
2 answers

Angular doesn’t allow you to display html right away, you have to say that it trusted, so change your success on this (make sure you have the $ sce dependency installed):

$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 as follows:

<p data-ng-bind-html="fArticle.trustedBody"></p>

: https://docs.angularjs.org/api/ng/directive/ngBindHtml, : ng-bind-html-unsafe, HTML?

+1

All Articles