SoFunction
Updated on 2025-04-13

Examples of $parse service and $eval service usage in AngularJS

1. $parse service

The $parse service can convert an expression into a function. This function can be called, and the arguments are a context object, usually scoped.
In addition, the function returned by the $parse expression has an assign property. This assign property is also a function that can be used to change the value of this expression in a given context.

<div my-attr="" my-directive>testing</div>
('myDirective',function($log, $parse) {
    return function(scope, elem, attrs) {
        //Parse "my-attr attribute value into a function"        var model = $parse();
        //Model is now a function, which can be called to get the value of the expression        //The following line of code will output the value in the scope        $(model(scope));
        ('click',function(){
        //'' is also a function, which is used to update the value of an expression        (scope,'New name');
        scope.$apply();
        })
    }
});

The above example fully demonstrates why we need the $parse service. If the property value is name, then we can do nothing to use $parse, just scope[]. But in the example above, square brackets don't work.

2. $eval service

$eval is a method in scope scope, which will execute an expression in the current scope and return the result:

 = 1;
 = 2;
scope.$eval('a+b'); // 3