$parse
和服务$interpolate
有什么区别$compile
?对我来说,他们都做同样的事情:获取模板并将其编译为模板函数。
问问题
47328 次
3 回答
466
这些都是帮助 AngularJS 视图渲染的服务示例(尽管$parse
并且 $interpolate
可以在此域之外使用)。为了说明每个服务的作用,让我们以这段 HTML 为例:
var imgHtml = '<img ng-src="/path/{{name}}.{{extension}}">'
范围内的值:
$scope.name = 'image';
$scope.extension = 'jpg';
鉴于此标记,这里是每个服务带来的内容:
$compile
- 它可以获取整个标记并将其转换为链接函数,当针对特定范围执行时,该函数会将一段 HTML 文本转换为动态的实时 DOM,其中所有指令(此处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 中提供实时 UI。但它们在不同的层面上运作:
$parse
仅关注单个表达式 (name
,extension
)。它是一种读写服务。$interpolate
是只读的,涉及包含多个表达式的字符串 (/path/{{name}}.{{extension}}
)$compile
是 AngularJS 机器的核心,可以将 HTML 字符串(带有指令和插值表达式)转换为实时 DOM。
于 2013-07-27T18:36:31.187 回答
4
$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。
于 2017-05-06T15:06:14.747 回答
0
这是可爱的解释。
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.
于 2018-06-05T06:55:02.290 回答