2013-07-27 32 views
169

$parse,$interpolate$compile服務有什麼區別? 對我來說,他們都做同樣的事情:採取模板並將其編譯爲模板函數。

回答

453

這些都是幫助AngularJS視圖渲染的服務示例(儘管$parse$interpolate可以在此域外使用)。爲了說明什麼是每個服務的角色讓我們這塊HTML的例子:

var imgHtml = '<img ng-src="/path/{{name}}.{{extension}}">' 

和範圍值:

$scope.name = 'image'; 
$scope.extension = 'jpg'; 

鑑於這種標記這裏是每個服務帶來的表:

  • $compile - 它可以把整個標記,並把它變成一個鏈接功能,當對一定範圍內執行將變成一段HTML文本與人的動態,實時DOM l指令(這裏:ng-src)對模型變化作出反應。我們可以像下面這樣調用它:$ compile(imgHtml)($ scope),並且會得到一個包含所有DOM事件邊界的DOM元素。 $compile正在利用$interpolate(除其他外)來完成其工作。
  • $interpolate知道如何處理帶嵌入式插值表達式的字符串,例如:/path/{{name}}.{{extension}}。換句話說,它可以帶有插值表達式的字符串,一個範圍並將其轉化爲結果文本。可以認爲$interpolation服務是一種非常簡單的基於字符串的模板語言。鑑於上面的例子,人們會使用這樣的服務,如:$interpolate("/path/{{name}}.{{extension}}")($scope)以得到path/image.jpg字符串。
  • $parse$interpolate用於針對範圍評估單個表達式(name,extension)。它可以用於給定表達式的讀取集合值。例如,要評估name表達式,可以執行:$parse('name')($scope)以獲取「圖像」值。要設置值將做:$parse('name').assign($scope, 'image2')

所有這些服務都在一起工作,以提供一個在AngularJS的生活用戶界面。但是,他們在不同的層面進行操作:

  • $parse僅涉及單個表達式(nameextension)。這是一個讀寫服務。
  • $interpolate是隻讀的,涉及包含多個表達式(/path/{{name}}.{{extension}}
  • $compile是AngularJS機械的心臟,可以將HTML字符串(與指令和插補表達式)到現場DOM字符串。
+11

很好解釋。投票了! :) – AlwaysALearner

+0

確實很不錯! –

+2

不錯。你能否提供每個人的例子用法和結果?它仍然不是100%清楚,我認爲這會有很大幫助。謝謝! –

5
$interpolate--> 

Let us say you have two variables assigned to $scope object in the controller, 

$scope.a = 2; 
$scope.b = 3; 

var f = $interpolate("Result is : {{a*b}}"); 
var result = f($scope); 
console.log(result); --->'Result is 6' 

This means that $interpolate can take the string which has one or more angular expressions. 

Now $parse: 

var f1 = $parse("a*b"); 
var result1 = f1($scope); 
console.log(result1); ----> '6' 

**So $interpolate has the capability to evaluate a string with angular expressions mixed up in the string against the scope to get the result**. 


Another important difference between $interpolate and $parse,$eval is: 

**$interpolate has the capability to work with strings containing filters along with angular expressions.** 

This feature is not accessible in $eval , $parse. 

console.log($interpolate("Result is : {{a*b | currency : 'USD$'}}")($scope)); 

---> 'Result is USD $6.00' 

$插值不必在$範圍變量的寫訪問,因爲我們有在$ EVAL和$解析

$解析,$插值--->必須注射但是$ EVAL不必在控制器中注入或它是用於

$解析,$插值給它可以對任何方面進行評估,但$ EVAL總是反對$範圍評估功能。

$ eval和$ interpolate在幕後只使用$ parse。

相關問題