ng-bind指令

概述

ng-bind指令是一個把數(shù)據(jù)模型里的數(shù)據(jù)和元素綁定的指令,ng-bind實際上有三種形式的指令:

指令名稱 指令說明
ng-bind 直接把數(shù)據(jù)綁定到元素的text上去,不會進行過多的處理
ng-bind-html 把數(shù)據(jù)作為一個html綁定到元素上,相當于調(diào)用.html()函數(shù)
ng-bind-template 可以處理多個數(shù)據(jù)表達式的綁定

詳細說明

ng-bind指令

ng-bind指令會把數(shù)據(jù)賦值給element的textContent,核心代碼如下:

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

其中stringify函數(shù)實現(xiàn)了對數(shù)據(jù)格式化成字符串的功能。具體轉(zhuǎn)換方式如下:

類型 處理方式
null 返回空字符串['']
string 返回原字符串
number 轉(zhuǎn)換成字符串返回
有自定義toString并且不是Array和Date的對象 返回toString的結(jié)果
其它 轉(zhuǎn)換成json返回

ng-bind-html指令

ng-bind-html指令會把處理過的數(shù)據(jù)通過element的html方法設(shè)置到元素上去,核心代碼如下:

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

這里實際上有三步:
1、根據(jù)scope得到最新的數(shù)據(jù)
2、把原數(shù)據(jù)轉(zhuǎn)換成可信任的html數(shù)據(jù)
3、調(diào)用html()函數(shù)設(shè)置內(nèi)容
其中第二步需要特別注意,如果沒有引入ngSanitize將會報錯。

ng-bind-template指令

ng-bind-template指令可以同時綁定多個數(shù)據(jù)以及表達式,每一個數(shù)據(jù)或表達式使用雙花括號包起來。其核心代碼:

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進行監(jiān)控,所以在綁定的時候每一個表達式必須使用雙花括號。
從代碼可以看出最終數(shù)據(jù)是被賦值到元素的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>

這段代碼主要實現(xiàn)的功能是把同一段html字符串使用三種不同的綁定方式進行數(shù)據(jù)綁定。其中ng-bind的方式會直接輸出html字符串,ng-bind-html會轉(zhuǎn)換成html標簽,ng-bind-template會把html字符串輸出兩次,中間使用橫線連接。

最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時請結(jié)合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容