将角绑定对象元素转换为HTML

时间:2016-09-08 02:46:41

标签: javascript html angularjs ng-bind-html ng-bind

我从另一个问题得到了代码,它很简单,工作正常

        if((newChange-change != 0 && newChange >= 1)) `

假设,我正在获取一个对象,我想显示一个对象的元素

<div ng-controller="ExampleController">
<p ng-bind-html="testHTML"></p>
(function(angular) {
  'use strict';
  angular.module('bindHtmlExample', ['ngSanitize'])
  .controller('ExampleController', ['$scope', function($scope) {
       $scope.testHTML = 'I am an <code>HTML</code>string with ' +
                         '<a href="#">links!</a> and other <em>stuff</em>';
  }]);
})(window.angular);

那么我应该如何只绑定html端的描述? 我试过了 var obj = { title: 'Title', description: 'I am an <code>HTML</code>string with ' + '<a href="#">links!</a> and other <em>stuff</em>' }; $scope.testHTML = obj; ,并 <p ng-bind-html="{{testHTML.description}}"></p>

plnkr example

3 个答案:

答案 0 :(得分:2)

尝试使用此代码段绑定HTML

首先,您可以创建自定义过滤器以在AngularJS中绑定HTML。

现在,只需编写yourHTML | html,就可以在myApp模块的任何位置使用此过滤器,这样就完成了工作。

&#13;
&#13;
var myApp = angular.module('myApp',[]);
myApp.controller('GreetingController', ['$scope','$sce', function($scope, $sce) {
  var obj = {
     title: 'Title',
     description: 'I am an <code>HTML</code>string with ' +
       '<a href="#">links!</a> and other <em>stuff</em>',
     description1: 'I am an <b>HTML</b>string with ' +
       '<a href="#">links!</a> and other <u><b>stuff</b></u>'
    
  };
  $scope.testHTML = obj;
  
  //Use $SCE in controller
  var preview_data = obj.description;
  $scope.htmlSafe = $sce.trustAsHtml(preview_data);
  
}]);
//Custom filter (Alternate way)
myApp.filter('html', ['$sce', function ($sce) { 
    return function (text) {
        return $sce.trustAsHtml(text);
    };    
}])
&#13;
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<div ng-app="myApp" ng-controller="GreetingController">
  
  <b>By using custom filter</b>
  <div ng-bind-html="testHTML.description | html"></div>
  <div ng-bind-html="testHTML.description1 | html"></div>

  <br/>
  <b>By using $SCE inside controller</b>
  <div ng-bind-html="htmlSafe"></div>

</div>
&#13;
&#13;
&#13;

答案 1 :(得分:0)

在html文件的plnkr示例中:

<p ng-bind-html="{{testHtml.desc}}"></p>更改为<p ng-bind-html="testHtml.desc"></p>,如下所示:

<body ng-app="bindHtmlExample">
  <div ng-controller="ExampleController">
 <p ng-bind-html=testHtml.desc></p>
</div>

答案 2 :(得分:0)

ng-bind-html在接受表达式时不需要插值,因此您只需将其设置为testHtml.desc而不使用花括号{{}}

在您的plunkr控制器中,您在声明obj之前将$scope.testHtml分配给obj,因此它不会在{obj之后呈现任何内容1}}在分配时未定义。

Plunkr:https://plnkr.co/edit/GvujCcYdCqLvwwnuEnWp?p=preview