ngBind ngBindTemplate ngBindHtml

ng-bind: 只能绑定一个变量

  在AngularJS中显示模型中的数据有两种方式:

  一种是使用花括号插值的方式:

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

  另一种是使用基于属性的指令,叫做ng-bind:

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

ng-bind-template:  可绑定多个变量    

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

输出结果:

ngBindTemplate(ng-bind-template)与ngBind不同之处在于:ngBind只能单个绑定变量,且变量无需使用双括号“{{}}”,而ngBindTemplate则可以绑定一个模板,模板中可以包含多个AngularJS的表达式:“{{expression}}”。

ng-bind-html: 

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

上面这ng-bind-html写法不能将titleHtml显示出来,在控制台中会报如下错误:

https://docs.angularjs.org/error/$sce/unsafe  点开此链接,会给出错误的原因及解决方法;

ngBindHtml(ng-bind-html)可以将一个字符串以安全的方式插入到页面中并显示成Html。

ngBindHtml将强制使用angular-santitize服务进行安全检查,由于并非包含在AngualrJS核心库中,因此需要引入angular-santitize.js文件,并在定义ngModule时添加对于ngSantitize的依赖声明。

解决方法一:

  1、引入angular-santitize.js文件

     2、将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>");
             }]);

转载于:https://www.cnblogs.com/loveamyforever/p/6089990.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值