0

http://jsfiddle.net/jffnojL1/

Here I am having a simple html element which I am trying to bind to Html using ng-bind-html.

But this doesn't seems to be working:

.controller('foo', function($scope) {
    $scope.bar = "<h1>this is bar</h1>";
    $scope.bar1 = "<h1> <a ng-href='www.google.com'> this is bar </a></h1>";
});

<div ng-controller="foo">

    <div ng-bind-html="bar1"></div>

</div>

If I use normal href, it works fine. Can anyone please explain why ng-href not working in this case or let me know how to make this work.

undefined
  • 3,464
  • 11
  • 48
  • 90
  • Hi everyone.. as I mentioned it works fine, if I use href. So my question is why ng-href not working here. How to make ng-href work here – undefined Jul 18 '17 at 12:14
  • 2
    The reason `ng-href` doesn't work here is because `ng-bind-html` does not compile any `ng-*` directives within the binded HTML. `href` is the way to go, and is actually what [the example in the official docs does here](https://docs.angularjs.org/api/ng/directive/ngBindHtml). – Matthew Cawley Jul 18 '17 at 12:40
  • 1
    This is not a duplicate of [this post](https://stackoverflow.com/q/43317123/6712896) @Sajeetharan – JeanJacques Jul 18 '17 at 12:49

3 Answers3

0

Try use this. Because you are using ng in your template so you should complie it or remove it.

 $scope.bar1 = "<h1> <a href='www.google.com'> this is bar </a></h1>";

Demo

Hadi J
  • 16,989
  • 4
  • 36
  • 62
0

use trustAsHtml in order to evaluete safe content. also use href insted of ng-href

angular.module("app",[])
.controller("ctrl",function($scope,$sce){
$scope.bar = "<h1>this is bar</h1>";
    $scope.bar1 = "<h1> <a href='www.google.com'> this is bar </a></h1>";
    
    $scope.bar1 = $sce.trustAsHtml($scope.bar1)

})
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<div ng-app="app" ng-controller="ctrl">
 <div ng-bind-html="bar1"></div>
</div>
Sachila Ranawaka
  • 39,756
  • 7
  • 56
  • 80
0

Just use href like

  $scope.bar1 = "<h1> <a href=\"http://www.google.com\"> this is bar </a></h1>";

See Here

suraj mahajan
  • 832
  • 1
  • 12
  • 21