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>");
             }]);
相关文章
相关标签/搜索