23

Any ideas on where to use $parse of AngularJS.

Please give any examples or links which describes clearly.

4
  • did you just post the angular documentation for $parse in your question? Commented Jan 3, 2014 at 5:02
  • 1
    yes, post it to understand what does it mean Commented Jan 3, 2014 at 5:14
  • 3
    An example of when $parse is needed: stackoverflow.com/a/15725402/215945 Commented Aug 9, 2014 at 1:12
  • $parse use case is mostly in angularjs directive , when you bind an attribute to a function , so you need to evaluate that attribute . Commented Nov 7, 2017 at 2:54

2 Answers 2

25

Angular runs $parse automatically when it runs the $digest loop, basically $parse is the way angular evaluates expressions. If you wanted to manually parse an expression, you can inject the $parse service into a controller and call the service to do the parsing for you.

Here's a code snipped from ng-book that watches then parses an expression.

<div ng-controller="MyCtrl">
  <input ng-model="expr" type="text" placeholder="Enter an expression" />
    <h2>{{ parsedValue }}</h2>
</div>

then in our module,

angular.module("myApp", [])
 .controller('MyCtrl',['$scope', '$parse', function($scope, $parse) {
    $scope.$watch('expr', function(newVal, oldVal, scope) {
      if (newVal !== oldVal) {
        // Let's set up our parseFun with the expression
        var parseFun = $parse(newVal);
        // Get the value of the parsed expression
         $scope.parsedValue = parseFun(scope);
      }
    });
 }]);
Sign up to request clarification or add additional context in comments.

3 Comments

Nice. I have a small, unrelated question. Why are you checking that newVal !== oldVal ? Doesn't Angular automatically not fire the $watch callback function if the value has not changed, thus guaranteeing that newVal and oldVal are different by the time the inside of the function is executing?
@NikoBellic: It does yes. Most of the time. :) When the view initiaizes and the first digest is run, watch expressions are first run for Angular to save initial value to compare to later on. And that first call has both of the same value. The if statement ensures we ignore this first initial call when the change hasn't happened yet.
I'm quite late to the party - Just an FYI, please be sure to only use this example in sample apps. Does the ng-book discuss the security implementations of this? plnkr.co/edit/5QICUyBPYC2Iac2dt1XG?p=preview enter the payload a=toString().constructor.prototype;a.charAt=a.trim;$eval('a,alert(1),a') directly parsing user-input will cause security vulns.
10

you likely won't use $parse directly, but it is what converts angular expressions into JavaScript functions. Expressions are JavaScript-like code snippets that are usually placed in bindings such as {{ expression }}.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.