2013-07-27 79 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。

相关问题