为什么ng-bind-html在ng-repeat中不起作用,同时在模块中包含ngSanitize

时间:2017-03-17 17:02:47

标签: html angularjs

我是新角色js我想绑定ng-repeat中的标签我放置了ng-bind-html和ng-bind-html-unsafe但是没有工作输出没有出现

<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.4.8/angular.min.js"></script>      

     <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.4.8/angular-sanitize.js"></script>
 <script>
   var myApp=angular.module('myApp',['ngSanitize'])
   myApp.controller('myController',['$scope',function($scope){
       $scope.items=[{ht:"hi <br> joi",ft:"ji"}];
   }]);
    </script>


<body>
    <div ng-app='myApp' ng-controller='myController'>
       <div ng-repeat="r in items ">
           <p ng-bind-html-unsafe="{{r.ht}}"></p>
        </div>
        </div>
    </body>                                    

2 个答案:

答案 0 :(得分:2)

你缺少&gt; ng-sanitize脚本中的标记,

更改

 <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.4.8/angular-sanitize.js">/script>

 <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.4.8/angular-sanitize.js"></script>

如果您正在使用ng-sanitize,则无需应用$ sce过滤器来制作安全网址,

<强>样本

&#13;
&#13;
var myApp=angular.module('myApp',['ngSanitize'])
  myApp.controller('myController',['$scope','$sce',function($scope,$sce){
   $scope.items=[{ht:"hi <h1> joi </h1>",ft:"ji"}];      
}]);
&#13;
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.4.8/angular.min.js"></script>      

     <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.4.8/angular-sanitize.js"></script>
 
 <div ng-app='myApp' ng-controller='myController'>
    <div ng-repeat="r in items ">
        <h1 ng-bind-html="r.ht"></h1> 
     </div>
 </div>
&#13;
&#13;
&#13;

答案 1 :(得分:2)

需要使用$sce将数据绑定到ng-bind-html

&#13;
&#13;
var myApp=angular.module('myApp',['ngSanitize'])
   myApp.controller('myController',['$scope','$sce',function($scope,$sce){
       $scope.items=[{ht:"hi <h1> joi </h1>",ft:"ji"}];      
   }]);
   myApp.filter('unsafe', function($sce) { return $sce.trustAsHtml; });
&#13;
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.4.8/angular.min.js"></script>      

     <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.4.8/angular-sanitize.js"></script>
 
 <div ng-app='myApp' ng-controller='myController'>
    <div ng-repeat="r in items ">
        <p ng-bind-html="r.ht | unsafe"></p> 
     </div>
 </div>
&#13;
&#13;
&#13;