ngBind ngBindTemplate ngBindHtml

ng-bind: 只能綁定一個變量html

  在AngularJS中顯示模型中的數據有兩種方式:angularjs

  一種是使用花括號插值的方式:express

  <p>{{titleStr}}</p>

  另外一種是使用基於屬性的指令,叫作ng-bind:安全

  <p><span ng-bind="titleStr"></span></p>

ng-bind-template:  可綁定多個變量    ui

<p ng-bind-template="{{titleStr}}&&{{titleStr2}}"></p>
$scope.titleStr = "angularjs中的title";
$scope.titleStr2 = "title";

輸出結果:spa

ngBindTemplate(ng-bind-template)與ngBind不一樣之處在於:ngBind只能單個綁定變量,且變量無需使用雙括號「{{}}」,而ngBindTemplate則能夠綁定一個模板,模板中能夠包含多個AngularJS的表達式:「{{expression}}」。code

ng-bind-html: htm

<p ng-bind-html="titleHtml"></p>
angular.module('myApp',[])
        .controller('myCtrl',['$scope',function($scope){
               $scope.titleHtml = "<h2>title</h2>";
        }]);

上面這ng-bind-html寫法不能將titleHtml顯示出來,在控制檯中會報以下錯誤:blog

https://docs.angularjs.org/error/$sce/unsafe  點開此連接,會給出錯誤的緣由及解決方法;ip

ngBindHtml(ng-bind-html)能夠將一個字符串以安全的方式插入到頁面中並顯示成Html。

ngBindHtml將強制使用angular-santitize服務進行安全檢查,因爲並不是包含在AngualrJS核心庫中,所以須要引入angular-santitize.js文件,並在定義ngModule時添加對於ngSantitize的依賴聲明。

解決方法一:

  一、引入angular-santitize.js文件

     二、將ngSanitize注入到module中

     代碼以下:

<script src="../angular-sanitize.min.js"></script>
<script>
        angular.module('myApp',['ngSanitize'])  <!--將ngSanitize注入到module中-->
.controller('myCtrl',['$scope',function($scope){
$scope.titleHtml
= "<h2>title</h2>";
}]);
</script>

參考:http://www.tuicool.com/articles/Q7VNJj 

解決方法二:

        使用$sce服務,將$sce服務注入到controller中,再使用$sce的trustAsHtml方法

        不須要引入額外的js文件,只須要將$sce服務注入到controller便可:

      angular.module('myApp',[])
            .controller('myCtrl',['$scope','$sce',function($scope,$sce){
                $scope.titleHtml = $sce.trustAsHtml("<h2>title</h2>");
             }]);
相關文章
相關標籤/搜索