这些都是帮助 AngularJS 视图呈现的服务示例(尽管 $parse和 $interpolate可以在此域之外使用)。为了说明每个服务的作用,让我们以这段 HTML 代码为例:
var imgHtml = '<img ng-src="/path/\{\{name}}.\{\{extension}}">'
范围和价值:
$scope.name = 'image';
$scope.extension = 'jpg';
这里给出的标记是每个服务带来的结果:
$compile-它可以将整个标记转换成一个链接函数,当在一定范围内执行时,会将一段 HTML 文本转换成动态的,带有所有指令(这里是 ng-src)的实时 DOM 来响应模型更改。我们可以按照以下方式调用它: $edit (imgHtml)($scope) ,并得到一个包含所有 DOM 事件界限的 DOM 元素。$compile正在利用 $interpolate(以及其他一些东西)来完成它的工作。
$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'
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.