1

I want to know, if it's possible to print some html tags (text with anchors) from $scope variable to output view? Look at the fiddle, I'm trying to print anchors from my database, but they are sometimes hidden in text. Thank you very much! :)

html:

<div ng-app>
  <h2>Html test</h2>
  <div ng-controller="TodoCtrl">
    <p data-ng-repeat="line in anchors">
      {{line}}
    </p>
  </div>
</div>

controller:

function TodoCtrl($scope) {
  $scope.anchors = [
    "<a href='#'>Something</a>", 
    "Angular ignores html tags :("
  ];
}
3
  • Don't use <a href="#">. we're not using HTML3.2 anymore, the # has had a very clear meaning since 1998: it's a uri fragment identifier for the top of the document, and will scroll your page if you use it for a link element. If you don't need a navigating link, but you need "to click and trigger javascript", we have <button> for that. Commented Dec 3, 2015 at 17:40
  • Look at this enter link description here Commented Dec 3, 2015 at 17:40
  • I'll fill the href attribute with a value, this is just an example. Commented Dec 3, 2015 at 17:43

2 Answers 2

3

Yes it is possbly with ng-bind-html directive

angular.module('app',['ngSanitize'])
.controller('TodoCtrl',
function TodoCtrl($scope) {
  $scope.anchors = ["<a href='#'>Something</a>", "Angular not ignores html tags :)"];
});
h2 {
  font-size: 18px;
  font-weight: bold;
  margin-bottom: 1em;
}
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular-sanitize.js"></script>
<div ng-app="app">
  <h2>Html test</h2>
  <div ng-controller="TodoCtrl">
    <p data-ng-repeat="line in anchors" ng-bind-html="line">
      
    </p>
  </div>
</div>

Sign up to request clarification or add additional context in comments.

Comments

0

If you mark the HTML as trusted you can inject it into the DOM with ng-bind-html.

angular.module('myApp', [])
  .directive('myDirective', function($sce){
    return {
        link: function(scope) {
          scope.trustedHTML = $sce.trustAsHtml('<h1>This is html</h1><h2>Subtitle</h2>');
        }
    }
  })
<script src="https://cdnjs.cloudflare.com/ajax/libs/angular.js/1.5.0-beta.2/angular.js"></script>

<div ng-app="myApp" my-directive>
    <div data-ng-bind-html="trustedHTML"></div>
</div>

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.