Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

$parse vs $eval ? which one is best practice?

Tags:

angularjs

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 ?

like image 651
Mukund Kumar Avatar asked Apr 25 '15 21:04

Mukund Kumar


3 Answers

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);
like image 199
New Dev Avatar answered Nov 07 '22 08:11

New Dev


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.

like image 20
sfletche Avatar answered Nov 07 '22 10:11

sfletche


$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:

  1. $eval always evaluates the expression based on the current scope and returns the result Example: console.log($scope.$eval("a*b")); // 8

  2. $parse just returns the function and does not work on any scope. Example:

    var func = $parse("a*b");
    

now func can be applied against

  1. any scope

    var result = func($scope);
    console.log(result); // 8
    
  2. 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.

like image 2
Dhana Avatar answered Nov 07 '22 09:11

Dhana