Understanding $parse service in AngularJS

Angular JS – the most popular SPA (Single Page Application) web application framework which has been selected as main structure of various web applications – it was a start-up team at first but then became google product.

Let’s pass away from angular itself and talk about $parse service. As this quotation from angular official documentation

Converts Angular expression into a function.

Angular expressions are JavaScript-like code snippets that are mainly placed in interpolation bindings such as <span title="{{ attrBinding }}">{{ textBinding }}</span> , but also used directly in directive attributes such as ng-click="functionExpression()" .

And here is some example of angular expression.

  1. 1+2
  2. a+b
  3. user.name
  4. items[index]

for getting more information please follow up this link.

Angular Expressions

So I don’t want to make it complex for you, so let's say with $parse you can manipulate objects with getter and setter. How? I’ll tell you, check this out.

var myObject = {
    name: 'ehsan',
    details: {
        age: 24

// get value
var age = $parse('details.age')(myObject);

// set value
$parse('details.hairColor').assign(myObject, 'Black');

In the above code if you log “age” variable it will contain “ehsan” String. Also after $parse if you log whole myObject you will see one more property “hairColor” added to “details” Object.

In addition I have to say $parse get 1 Parameter as String which is expression context to be compiled and it will return function as return value. one the most important properties of the retuned function is “assign” for checking whether the expression is assignable or not, if it is, it will change that value on the given context.

We can also talk more about $parse in specific details like, literal & context & locals, but I think these are complex and you do not need them occasionally.


No Comments Yet