一、何為插值字符串?
其實插值字符串的意思就是:擁有字符插值標記的字符串。
如: hello,{{ to }}....
字符插值標記:相當於我們平時在字符串替換中使用到的占位符。
上面的例子中的{{to}}其實就是類似於一個占位符,我們可以通過$interpolate服務將上面的例子中的字符串進行處理,返回一個模板對象,由於$interpolate服務默認是將{{、}}分別當做是占位符的前綴和后綴,所以,上面的例子中的{{to}}將會被當做一個占位符,並且把to當做該占位符的命名,可以給模板對象傳入一個對象如:{to:'xxxx'},直接替換掉{{to}}占位符。
二、來個栗子!
<!DOCTYPE html> <html> <head> <meta charset=utf-8 /> <title>JS Bin</title> </head> <body ng-app="myApp"> <div ng-controller="MyController"> <input ng-model="to" type="email" placeholder="Recipient" /> <textarea ng-model="emailBody"></textarea> <pre>{{ previewText }}</pre> <script src="https://rawgit.com/angular/bower-angular/master/angular.min.js"></script> </div> </body> </html>
angular.module('myApp',[])
.controller('MyController',function($scope,$interpolate){
$scope.emailBody = "hello,{{to}}";
$scope.to = 'ari@fullstack.io';
var template = $interpolate($scope.emailBody);
$scope.$watch('to',function(to){
console.log(to);
$scope.previewText = template({'to':$scope.to});
});
});
代碼片段:JS Bin on jsbin.com
三、$interpolate服務
$interpolate服務是一個可以接受三個參數的函數,其中第一個參數是必需的。
- text(字符串):一個包含字符插值標記的字符串。
- mustHaveExpression(布爾型):如果將這個參數設為true,當傳入的字符串中不含有表
達式時會返回null。 - trustedContext(字符串): AngularJS會對已經進行過字符插值操作的字符串通過
$sec.getTrusted()方法進行嚴格的上下文轉義。
$interpolate服務返回一個函數,用來在特定的上下文中運算表達式。
四、如何改變占位符的前、后綴?
上面的第一點就講到了$interpolate默認的占位符是以{{、}}為前后綴的。
那這個占位符的前后綴能否改成我們自己想要的樣子呢?
答案是肯定的,當然可以改~~
我們只需要在$interpolateProvider服務進行配置。
$interpolateProvider.startSymbol('__');
$interpolateProvider.endSymbol('__');
注意:使用$interpolateProvider進行設置這個占位符的前后綴的時候,需要注意你的上下文,如果你是直接在某個模塊下進行配置,那么該模塊的angularjs數據綁定對象的{{xxx}}格式也會被影響。
如:
angular.module('myApp',[])
.config(['$interpolateProvider',function($interpolateProvider){
$interpolateProvider.startSymbol('__');
$interpolateProvider.endSymbol('__');
}])
.controller('MyController',function($scope,$interpolate){
$scope.emailBody = "hello,__to__";
$scope.to = 'ari@fullstack.io';
$scope.previewText ="";
var template = $interpolate($scope.emailBody);
$scope.$watch('to',function(to){
console.log(to);
$scope.previewText = template({'to':$scope.to});
console.log($scope.previewText);
});
});
那么html頁面中{{previewText}}就也要改成__previewText__的格式.
<!DOCTYPE html> <html> <head> <meta charset=utf-8 /> <title>JS Bin</title> </head> <body ng-app="myApp"> <div ng-controller="MyController"> <input ng-model="to" type="email" placeholder="Recipient" /> <br/> <textarea ng-model="emailBody"></textarea> <br/> <pre>__previewText__</pre> <script src="https://rawgit.com/angular/bower-angular/master/angular.min.js"></script> </div> </body> </html>
所以,一般情況下$interpolateProvide用在自己創建的服務上面,這樣就可以把上下文環境進行隔離。
代碼片段:JS Bin on jsbin.com
