$parse、$interpolate和$compile服务之间有什么区别?对我来说,它们都做同样的事情:获取模板并将其编译为template-function。
发布于 2013-07-28 02:36:31
这些都是有助于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 (以及其他东西)来做它的job.$interpolate知道如何处理带有内嵌插值表达式的字符串,例如:/path/{{name}}.{{extension}}。换句话说,它可以接受一个带有插值表达式的字符串,一个作用域,并将其转换为结果文本。可以将$interpolation服务看作是一种非常简单的、基于字符串的模板语言。在上面的例子中,我们将使用如下服务: result.$parse使用$interpolate("/path/{{name}}.{{extension}}")($scope)来获取path/image.jpg字符串,而$interpolate使用它来针对某个作用域计算单个表达式(name,extension)。它可用于读取和设置给定表达式的值。例如,要计算图像表达式:$parse('name')($scope)以获得“name”值。要设置该值,请执行以下操作:$parse('name').assign($scope, 'image2')所有这些服务协同工作,在AngularJS中提供实时UI。但它们在不同的层次上运行:
$parse只关注单个表达式(name、extension)。它是一个读写的service.$interpolate,是只读的,与包含多个表达式的字符串相关。(/path/{{name}}.{{extension}})$compile是AngularJS机制的核心,可以将HTML字符串(带有指令和插值表达式)转换为活动的DOM。发布于 2017-05-06 23:06:15
$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。
发布于 2018-06-05 14:55:02
这是一个有趣的解释。
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.https://stackoverflow.com/questions/17900588
复制相似问题