AngularJS data bind in ng-bind-html?

后端 未结 3 502
走了就别回头了
走了就别回头了 2020-11-29 07:57

Is it possible to bind data of scope variable to a html that is about to bind as ng-bind-html?

ie, I have a

html =\"
{{caption}}
相关标签:
3条回答
  • 2020-11-29 08:09

    What about?

    html = '<div ng-bind="caption"></div>';

    0 讨论(0)
  • 2020-11-29 08:21

    You should use $interpolate not $compile.
    Write controller like this:

    angular.module('app', ['ngSanitize'])
      .controller('MyCtrl', ['$scope', '$interpolate', function($scope, $interpolate){
       $scope.caption = 'My Caption';
       $scope.html = $interpolate('<div>{{caption}}</div>')($scope);
    });
    

    Then write HTML like this:

    <div ng-controller="MyCtrl">
        <div ng-bind-html="html"></div>
    </div>
    
    0 讨论(0)
  • 2020-11-29 08:25

    You need to compile your HTML snippet, but it is recommended to do that inside the directive.

    app.controller('MyCtrl', function($compile){
      $scope.caption = 'My Caption';
      $scope.html = $compile('<div>{{caption}}</div>')($scope);
    });
    
    <div ng-bind-html="html"></div>
    
    0 讨论(0)
提交回复
热议问题