3

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?

2 Answers 2

2

$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);
    }
}
Sign up to request clarification or add additional context in comments.

2 Comments

Thanks for the reply.Also I wanted to know how $eval and $parse plays a role in $digest cycle i.e like when we are using these services in $digest cycle when we have an expression
@Kalaivani I recommend to look at the source of $digest for more research on this. Explaining that in detail is too broad for StackOverflow
1

$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);

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.