zoukankan      html  css  js  c++  java
  • 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>");
                 }]);
  • 相关阅读:
    实验 1:Mininet 源码安装和可视化拓扑工具
    Linux bond 网卡主备模式配置
    git常用命令总结
    框架搭建之--配置去除用户输入两边的空格
    性能优化之--数据库缓存
    性能优化之缓存--文件缓存
    网站优化之缓存--页面缓存
    网站优化之缓存--session和cache以及常用缓存应用之间的区别
    MVC请求管道详细总结梳理。
    sql优化记录
  • 原文地址:https://www.cnblogs.com/loveamyforever/p/6089990.html
Copyright © 2011-2022 走看看