![]() |
VOOZH | about |
The $parse service in AngularJS is a function that takes an expression string and returns a function that can be used to parse and evaluate the expression. The expression string can contain variables, operators, and function calls.
To use the $parse service, you first need to inject it into your AngularJS component as a dependency. For example, you might inject it into a controller like this:
angular.module('myModule', [])
.controller('MyController', function($scope, $parse) {
// Use the $parse service here
});Syntax:
var fn = $parse(expression); var result = fn(context, locals);
Parameter: It accepts the expression as a parameter which is a string containing the expression to be parsed and evaluated.
Return type: It returns the function which depicts the compiled expression:
Example 1: In this example, we have an AngularJS application with a single controller, MyController. We have injected the $parse service into the controller as a dependency. When the user enters an expression into the input element and clicks the "Evaluate" button, the evaluate function is called and the result is displayed in the <p> element.
Output:
Example 2: This example adds two input fields to the form, one for the first name and one for the last name. When the form is submitted, the updateFullName function is called, which updates the firstName and lastName properties on the scope with the values of newFirstName and newLastName, respectively, and re-evaluates the full name expression. This updates the value of $scope.fullName and the text displayed on the page.
Output: