Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

AngularJS : What is the difference between $eval() and $parse in AngularJS?

Tags:

angularjs

In some cases AngularJs documentation suggests we use eval() during the $digest cycle and in some case we are suggested to use parse() during $digest cycle? Can anyone give a good example when in $digest cycle we should use $eval() and $parse(), respectively?

like image 462
Kalaivani Avatar asked Aug 31 '26 10:08

Kalaivani


2 Answers

$parse takes an angular expression and returns a function that represents that expression.

$eval takes an angular expression, evaluates it and returns the actual result of that expression.

You can think of it like this (this is pseudo-example code to show what I mean, this is not how $parse actually works):

function $parse(expression) {
    return function() {
        return $eval(expression);
    }
}
like image 120
LionC Avatar answered Sep 03 '26 23:09

LionC


$parse is used to create a function based on defined objects / expressions, e.g:

var getter = $parse('user.name');
var setter = getter.assign;
var context = {user:{name:'angular'}};
var locals = {user:{name:'local'}};

expect(getter(context)).toEqual('angular');
setter(context, 'newValue');
expect(context.user.name).toEqual('newValue');
expect(getter(context, locals)).toEqual('local');

Simply with $parse you're able to create an OO Object with Getter, Setter, details are given at https://docs.angularjs.org/api/ng/service/$parse and Source: https://github.com/angular/angular.js/blob/master/src/ng/parse.js#L1678.

$eval is for retrieving a result based on an expression:

var scope = ng.$rootScope.Scope();
scope.a = 1;
scope.b = 2;

expect(scope.$eval('a+b')).toEqual(3);
expect(scope.$eval(function(scope){ return scope.a + scope.b; })).toEqual(3);

The interesting fact is that $eval is using $parse to create an function $eval implementation:

 $eval: function(expr, locals) {
        return $parse(expr)(this, locals);
      },

This is related to the fact, if I understand the $parse code right, that $parse checks what kind of expression and context (scope) you have. Basically, $eval is a shorthand use for something like (instead of doing it each time for your $scope Object in the controller for example):

var getter = $parse("a");
var setter = getter.assign;
scope.a = 1;

expect(getter(scope)).toEqual(1);
like image 21
Fer To Avatar answered Sep 03 '26 23:09

Fer To



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!