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>");
                 }]);
  • 相关阅读:
    iOS 成员变量,实例变量,属性变量的区别,联系
    iOS类别(category)不能添加成员变量但是可以添加属性的问题
    iOS缓存机制详解
    ios数据缓存方法
    仿360圆圈自动隐藏效果
    html 背景透明文字不透明
    netty
    关注网站
    关注URL
    DNS之XX记录
  • 原文地址:https://www.cnblogs.com/loveamyforever/p/6089990.html
Copyright © 2011-2022 走看看