ng-bind指令

概述

ng-bind指令是一个把数据模型里的数据和元素绑定的指令,ng-bind实际上有三种形式的指令:

指令名称 指令说明
ng-bind 直接把数据绑定到元素的text上去,不会进行过多的处理
ng-bind-html 把数据作为一个html绑定到元素上,相当于调用.html()函数
ng-bind-template 可以处理多个数据表达式的绑定

详细说明

ng-bind指令

ng-bind指令会把数据赋值给element的textContent,核心代码如下:

scope.$watch(attr.ngBind, function ngBindWatchAction(value) {
  element.textContent = stringify(value);
});

其中stringify函数实现了对数据格式化成字符串的功能。具体转换方式如下:

类型 处理方式
null 返回空字符串['']
string 返回原字符串
number 转换成字符串返回
有自定义toString并且不是Array和Date的对象 返回toString的结果
其它 转换成json返回

ng-bind-html指令

ng-bind-html指令会把处理过的数据通过element的html方法设置到元素上去,核心代码如下:

var value = ngBindHtmlGetter(scope);
element.html($sce.getTrustedHtml(value) || '');

这里实际上有三步:
1、根据scope得到最新的数据
2、把原数据转换成可信任的html数据
3、调用html()函数设置内容
其中第二步需要特别注意,如果没有引入ngSanitize将会报错。

ng-bind-template指令

ng-bind-template指令可以同时绑定多个数据以及表达式,每一个数据或表达式使用双花括号包起来。其核心代码:

var interpolateFn = $interpolate(element.attr(attr.$attr.ngBindTemplate));
$compile.$$addBindingInfo(element, interpolateFn.expressions);
element = element[0];
attr.$observe('ngBindTemplate', function(value) {
  element.textContent = isUndefined(value) ? '' : value;
});

需要注意的是这里使用的是attr.$observe进行监控,所以在绑定的时候每一个表达式必须使用双花括号。
从代码可以看出最终数据是被赋值到元素的textContent上的,所以这个是无法支持html字符串的。

样例说明:

<!DOCTYPE html>
<html lang="en" ng-app="app">
<!--<html>-->
<head>
    <title>Test</title>
</head>
<body>
<div ng-controller="ExampleController">
    <p ng-bind="myHTML"></p>
    <p ng-bind-html="myHTML"></p>
    <p ng-bind-template="{{myHTML}} ---- {{myHTML}}!"></p>
</div>
</body>
<script src="./node_modules/angular/angular.js" type="text/javascript"></script>
<script src="./node_modules/angular-sanitize/angular-sanitize.js" type="text/javascript"></script>
<script>
    angular.module('app', ['ngSanitize'])
            .controller('ExampleController', ['$scope', function ($scope) {
                $scope.myHTML =
                        'I am an <code>HTML</code>string with ' +
                        '<a href="#">links!</a> and other <em>stuff</em>';
            }]);
</script>
</html>

这段代码主要实现的功能是把同一段html字符串使用三种不同的绑定方式进行数据绑定。其中ng-bind的方式会直接输出html字符串,ng-bind-html会转换成html标签,ng-bind-template会把html字符串输出两次,中间使用横线连接。

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容