3

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.

2 Answers 2

5

$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'
Sign up to request clarification or add additional context in comments.

Comments

2

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.