$parse and $eval both operate on angular expressions i.e. {{ expression }}.
$eval is a scope method which executes an expression on the current scope and returns the result.
scope.a = 1;
scope.b = 2;
scope.$eval('a+b'); // 3
$parse is an Angular service which converts an expression into a function. Then function can be invoked and
passed a context (usually scope) in order to retrieve the expression's value.
<div my-attr="obj.name" my-directive>
dotnet-tricks.com
</div>
<script type="text/javascript">
myApp.directive('myDirective', function( $parse, $log ) {
return function( scope, el, attrs ) {
// parse the "my-attr" attribute value into a function
var myFn = $parse( attrs.myAttr );
// "myFn" is now a function which can be invoked to get the expression's value;
// the following line logs the value of obj.name on scope:
$log.log(myFn(scope) ); // dotnet-tricks.com
el.bind('click', function() {
// "myFn.assign" is also a function; it can be invoked to
// update the expresssion value
myFn.assign(scope, "New name");
scope.$apply();
})
}
});
</script>
Also, if the expression is assignable then the returned function will have an assign property. The assign property
is a function that can be used to change the expression's value on the given context.