$parse
、$interpolate
和$compile
服务有什么区别?对我来说,它们都是做同样的事情:将模板编译成模板函数。
$parse
、$interpolate
和$compile
服务有什么区别?对我来说,它们都是做同样的事情:将模板编译成模板函数。
这些都是帮助 AngularJS 视图渲染的服务示例(尽管 $parse
和 $interpolate
也可以在此领域之外使用)。为了说明每个服务的作用,让我们以这段 HTML 代码为例:
var imgHtml = '<img ng-src="/path/{{name}}.{{extension}}">'
并在作用域上赋予了值:
$scope.name = 'image';
$scope.extension = 'jpg';
给定这个标记,以下是每个服务所带来的功能:
$compile
- 它可以接受整个标记并将其转换为链接函数,当针对特定作用域执行时,将把HTML文本转换为动态、活动的DOM,并使所有指令(例如:ng-src
)响应模型更改。要调用它,可以按如下方式编译$compile
在执行工作时会使用$interpolate
等工具。$interpolate
知道如何处理包含嵌入式插值表达式的字符串,例如:/path/{{name}}.{{extension}}
。换句话说,它可以获取带插值表达式的字符串、作用域并将其转换为结果文本。人们可以将$interpolation
视为基于非常简单的字符串模板语言的服务。以上面的示例为例,使用此服务的方法是:$interpolate("/path/{{name}}.{{extension}}")($scope)
,结果将获得path/image.jpg
字符串。$parse
被$interpolate
用于计算作用域中的单个表达式(例如name
、extension
)。它可用于读取和设置给定表达式的值。例如,要计算name
表达式,可以执行:$parse('name')($scope)
,结果将获得值为"image"的字符串。要设置值,可以执行:$parse('name').assign($scope, 'image2')
所有这些服务共同工作,以在AngularJS中提供实时UI。但它们在不同级别上运作:
$parse
只涉及单个表达式(例如name
、extension
)。它是一个可读写服务。$interpolate
是只读的,并关注包含多个表达式的字符串(例如:/path/{{name}}.{{extension}}
)$compile
是AngularJS机器核心,可以将HTML字符串(带有指令和插值表达式)转换为活动DOM。$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'
$interpolate没有像$eval和$parse一样对$scope变量有写入访问权限。
$parse,$interpolate需要被注入,但是$eval不需要在控制器或使用它的地方被注入。
$parse,$interpolate提供了可以针对任何上下文进行评估的函数,但$eval总是针对$scope进行评估。
$eval和$interpolate在幕后都使用$parse。
这里是可爱的解释。
var img = img/{{name}}.{{extension}}
$parse - > (name,extension) = > vimal , .jpg
$interpolate -> use angular $parse and convert into string -> img/vimal.jpg
$compile -> can turn html string img/vimal.jpg into live DOM so new img tag will be added inside our DOM with all prototype that a img tag have.