In AngularJS, $compile
and $parse
are two powerful services used for dynamic content manipulation and evaluating expressions within the scope.
1. $compile
Service
The $compile
service in AngularJS compiles HTML strings or DOM elements into a template function, which can be linked to a scope to bind data dynamically.
Use Case:
- When you need to add dynamic directives or bind new elements to the AngularJS scope.
How It Works:
- Takes raw HTML as input.
- Compiles it into a function.
- Links it to the current scope to bind data.
Example: Dynamically Adding an AngularJS Directive
app.controller("CompileController", function($scope, $compile) {
$scope.addElement = function() {
var html = '<p>Hello, {{ name }}! This is dynamically compiled.</p>';
var compiledElement = $compile(html)($scope);
angular.element(document.getElementById("container")).append(compiledElement);
};
});
HTML:
<div ng-controller="CompileController">
<input type="text" ng-model="name" placeholder="Enter name">
<button ng-click="addElement()">Add Element</button>
<div id="container"></div>
</div>
This allows elements to be dynamically added and bound to $scope
without losing AngularJS functionality.
2. $parse
Service
The $parse
service evaluates AngularJS expressions dynamically and allows you to access or modify scope properties programmatically.
Use Case:
- When you need to evaluate expressions at runtime.
- When creating custom directives that need access to scope variables dynamically.
How It Works:
- Parses an AngularJS expression.
- Compiles it into a function.
- Executes it with a given scope.
Example: Evaluating an Expression Dynamically
app.controller("ParseController", function($scope, $parse) {
$scope.expression = "user.name";
$scope.user = { name: "Narendra" };
$scope.evaluateExpression = function() {
var getter = $parse($scope.expression);
$scope.result = getter($scope);
};
});
HTML:
<div ng-controller="ParseController">
<input type="text" ng-model="expression" placeholder="Enter an expression">
<button ng-click="evaluateExpression()">Evaluate</button>
<p>Result: {{ result }}</p>
</div>
This allows you to evaluate dynamic AngularJS expressions without hardcoding them.
3. Key Differences Between $compile
and $parse
Feature | $compile | $parse |
---|---|---|
Purpose | Compiles raw HTML into AngularJS templates. | Parses and evaluates AngularJS expressions. |
Works On | HTML elements & directives. | Expressions (like user.name or 1 + 2 ). |
Output | A function that links compiled HTML to scope. | A function that evaluates expressions dynamically. |
Use Case | Creating dynamic UI elements with scope bindings. | Evaluating and modifying scope variables dynamically. |
4. When to Use $compile
and $parse
?
Use $compile
when you need to dynamically generate HTML content that interacts with AngularJS.
Use $parse
when you need to evaluate expressions programmatically instead of using eval()
.