使用 AngularJs 的绑定 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

您可以使用指令编译 $scope 变量,因此您不需要 ngSanitize

演示版

 var app = angular.module("myApp", []);
 app.controller("myCtrl", function($scope,$sce) {
        $scope.myMarkup = "<h1>Hi {{name}}</h1>";
        $scope.name="Habib";
        $scope.trustAsHtml = function(html){
    return $sce.trustAsHtml(html);
  }
 });
 
 
app.directive('compileTemplate', function($compile, $parse){
    return {
        link: function(scope, element, attr){
            var parsed = $parse(attr.ngBindHtml);
            function getStringValue() {
                return (parsed(scope) || '').toString();
            }

            // Recompile if the template changes
            scope.$watch(getStringValue, function() {
                $compile(element, null, -9999)(scope);  // The -9999 makes it skip directives so that we do not recompile ourselves
            });
        }
    }
});
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>

<div ng-app="myApp" ng-controller="myCtrl">
    <p ng-bind-html="trustAsHtml(myMarkup)" compile-template></p>
</div>

app.controller("myCtrl", function($scope,$interpolate) {
    $scope.name="Habib";
    $scope.myMarkup = $interpolate('<h1>Hi {{name}}</h1>')($scope);
});

试试上面的代码。可能有帮助!! $compile$interpolate 的替代。你也可以试试。

您应该像这样使用 $interpolate:(注意您必须在标记之前声明内插值

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>