为什么要要$sce?因为AngularJS里好些地方,比如路径默认是个字符串,不会认为是路径,从而访问不到我们需要的东西,那么我们就可以通过$sce告诉angualrJS这个路径,这样是很安全滴。它有以下几种:
$sce.trustAs(type,name); $sce.trustAsUrl(value); $sce.trustAsHtml(value); $sce.trustAsResourceUrl(value); $sce.trustAsJs(value);
1.trustAsResourceUrl
<html> <head> <meta charset="utf-8"> <script src="/UploadFiles/2021-04-02/angular.min.js">2.trustAsHtml
<body> <div ng-app="myApp" ng-controller="myCtrl"> 未处理的: <div ng-repeat="item in formData"> {{item.name}} :{{item.htmlVal}} </div> <br/>处理过的:<button ng-click="look()">查看处理结果</button> <div ng-repeat="item in data"> {{item.name}} :<p ng-bind-html = "item.htmlVal"></p> </div> </div> <script> var app = angular.module('myApp', []); app.controller('myCtrl', function($scope,$sce){ //未处理数据源 $scope.formData=[ {"name":"张春玲","htmlVal":"我是<span style='color:red;'>张春玲<span>"}, {"name":"sb","htmlVal":"我是<span style='color:red;'>sb<span>"} ]; //处理结果 $scope.look = function(){alert $scope.data=[ {"name":"张春玲","htmlVal":"我是<span style='color:red;'>张春玲<span>"}, {"name":"sb","htmlVal":"我是<span style='color:red;'>sb<span>"} ]; for(var i=0;i<$scope.data.length;i++){ $scope.data[i].htmlVal = $sce.trustAsHtml($scope.data[i].htmlVal); } }; }); </script> </body>以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持。