Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

When to use $parse in Angular.js

How does the $parse provider in angular js work, In which cases would it be useful and in which cases would the assign fn be available.

like image 762
Praveen Avatar asked Apr 07 '26 03:04

Praveen


2 Answers

$parse is useful for evaluating a string and returning a function that can manipulate a model, or call a function. Any variables within the string is resolved from the context that is passed into the function.

Getting and Setting a Property of a Model

$parse is useful for compiling an angular expression into a function that can get/set a model.

For example, if you want to get/set user.name, you can use $parse('user.name'):

Getter

var context = { user: { name: 'john'}};
var getter = $parse('user.name');
var name = getter(context);
console.log(name); // outputs 'john'

Setter

var context = { user: { name: 'john'}};
var setter = $parse('user.name').assign;
setter(context, 'tom');
console.log(context.user.name); //outputs tom

$scope can also serve as the context:

$scope.user = { name: 'john' };
var getter = $parse('user.name');
var name = getter($scope);
console.log(name); // outputs 'john'

Calling a Function

$parse may also be used to compile an angular expression into a callable function.

For example, if you want to call a function called helloWorld():

var context = { 
      helloWorld: function(name) { 
           alert(name); 
      }, 
      user: {
           name:'john'
      }
};
var fn = $parse('helloWorld(user.name)');
fn(context); // alerts 'john'
like image 185
pixelbits Avatar answered Apr 09 '26 17:04

pixelbits


You want to use $parse when you want to convert angular expression into javascript function. Angular expression is a string such as {{ expression }}.

Take a look at this article. $parse

like image 31
Darshan P Avatar answered Apr 09 '26 15:04

Darshan P