23

Any ideas on where to use $parse of AngularJS.

Please give any examples or links which describes clearly.

Mosh Feu
  • 28,354
  • 16
  • 88
  • 135
rinesh
  • 327
  • 1
  • 3
  • 9

2 Answers2

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);
      }
    });
 }]);
Tyler McGinnis
  • 34,836
  • 16
  • 72
  • 77
  • 2
    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? – Niko Bellic Nov 03 '15 at 23:51
  • 2
    @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. – Robert Koritnik Aug 24 '16 at 13:42
  • 1
    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? https://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. – Lewis Sep 13 '16 at 11:19
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 }}.

Claies
  • 22,124
  • 4
  • 53
  • 77