I know that $parse
and $eval
both operate on Angular expressions.then why Angular team created these two ?
I checked in angular library, $eval
is defined like that:
$eval: function(expr, locals) {
return $parse(expr)(this, locals);
}
so what is difference between :
$parse(expr)(context, locals);
and
$eval: function(expr, locals) {
return $parse(expr)(this, locals);
}
I want to know which one is best practice ? and when to use these two ?
As you noticed,
$parse(expr)($scope, locals)
is exactly equivalent to
$scope.$eval(expr, locals)
But, $parse
is more "fundamental" operation than $eval
, and so, you could $parse
once in one place (for example, in compile
function of a directive):
var parsedExpr = $parse(tAttrs.p1);
and use repeatedly elsewhere (for example, in a controller
function)
var childScope1 = $scope.$new();
var childScope2 = $scope.$new();
var r1 = parsedExpr(childScope1);
var r2 = parsedExpr(childScope2);
I think the important difference is that $eval
is a scope
method that executes an expression on the current scope, while $parse
is a (more globally available) service.
So you can say $parse(expr)(context, locals);
, with any context, but in the case of $eval
the context
will be the scope
.
$eval behind the scenes uses $parse against the current scope.
Let us say you have
$scope.a = 2;
$scope.b = 4;
$parse("a*b")
gives you a function which has to be evaluated against the context/object/scope to get the result.
So now
var f = $parse("a*b");
var result = f($scope);
we are using the output of $parse which is a function applied against the $scope.
NOTE:
$eval
always evaluates the expression based on the current scope and returns the result
Example: console.log($scope.$eval("a*b")); // 8
$parse
just returns the function and does not work on any scope.
Example:
var func = $parse("a*b");
now func
can be applied against
any scope
var result = func($scope);
console.log(result); // 8
object
var result1 = func({a:3 , b:3});
console.log(result1); // 9
So same expression parsed once can be evaluated against any scope or object.
As said before , for $eval
angular uses $parse
against the current scope behind the scenes to evaluate the expression and return the result.
If you want multiple contexts to be executed for the same expression $parse
is the best choice.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With