angularjsangularjs-directiveangularjs-ng-modelng-bind-html

Variable is not showing in binded HTML using AngularJs


<div ng-app="myApp" ng-controller="myCtrl">
    <p ng-bind-html="myMarkup"></p>
</div>
<script>
    var app = angular.module("myApp", ['ngSanitize']);
    app.controller("myCtrl", function($scope) {
        $scope.myMarkup = "<h1>Hi {{name}}</h1>";
        $scope.name="Habib";
    });
</script>

Comming Output: Hi {{name}}

Desired Output: Hi Habib


Solution

  • You shoud use $interpolate like this: (Notice you must declare the interpolated value before the markup)

    var app = angular.module("myApp", ['ngSanitize']);
    app.controller("myCtrl", function($scope, $interpolate) {
      $scope.name = "Habib";
      $scope.myMarkup = $interpolate("<h1>Hi {{name}}</h1>")($scope);
    });
    <script src="https://cdnjs.cloudflare.com/ajax/libs/angular.js/1.6.4/angular.min.js"></script>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/angular.js/1.6.4/angular-sanitize.min.js"></script>
    <div ng-app="myApp" ng-controller="myCtrl">
      <p ng-bind-html="myMarkup"></p>
    </div>