首页 > 代码库 > service $sce or ng-bind-html

service $sce or ng-bind-html

ng-bind-html:
一般搭配 $sce.trutsAsResourceUrl $sce.trutsAsHtml

<html>
<head>
    <meta charset="utf-8">
    <script src="js/angular.js"></script>
</head>
<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":"小鸟","htmlVal":"我是<span style=‘color:red;‘>小鸟<span>"}
        ];

        //处理结果
        $scope.look = function(){
            $scope.data=[
                {"name":"大鸟","htmlVal":"我是<span style=‘color:red;‘>大鸟<span>"},
            {"name":"小鸟","htmlVal":"我是<span style=‘color:red;‘>小鸟<span>"}

            for(var i=0;i<$scope.data.length;i++){
                $scope.data[i].htmlVal = $sce.trustAsHtml($scope.data[i].htmlVal);
            }
        };

    });
</script>
</body>
</html>

 

service $sce or ng-bind-html