![]()
In AngularJS, both $compile and $interpolate are used for processing templates and expressions, but they serve different purposes.
$compile – Compiling and Linking Directives
$compile is a service that compiles an HTML string or DOM element into an AngularJS template. It processes directives (ng-model, ng-repeat, etc.) and creates a link function that binds the compiled template to a $scope.
Example of $compile
var app = angular.module("myApp", []);
app.controller("MainController", function ($scope, $compile) {
$scope.message = "Hello, AngularJS!";
$scope.addElement = function () {
var html = '<p>{{ message }}</p>'; // AngularJS expression
var compiledElement = $compile(html)($scope); // Compile and link with scope
angular.element(document.getElementById("output")).append(compiledElement);
};
});
Explanation:
$compile(html)($scope)processes directives and expressions inside the string.- The compiled element is linked to the scope, allowing two-way binding.
- The new element is appended dynamically to the DOM.
$interpolate – Evaluating Angular Expressions in Strings
$interpolate is a service that evaluates expressions inside {{ }} and returns a plain string. Unlike $compile, it does not process directives or bind the result to the scope.
Example of $interpolate
app.controller("MainController", function ($scope, $interpolate) {
$scope.username = "John Doe";
var template = "Welcome, {{ username }}!";
var interpolated = $interpolate(template)($scope); // Evaluates {{ username }}
console.log(interpolated); // Output: "Welcome, John Doe!"
});
Explanation:
$interpolate(template)($scope)replaces{{ username }}with"John Doe".- The result is a plain string, not an interactive binding.
Key Differences Between $compile and $interpolate
| Feature | $compile | $interpolate |
|---|---|---|
| Purpose | Compiles and links AngularJS templates, processing directives. | Evaluates expressions inside {{ }} and returns a plain string. |
| Scope Binding | Yes, links the template with $scope. | No, just evaluates expressions without scope binding. |
Processes Directives (ng-model, ng-repeat etc.)? | Yes | No |
Processes Expressions ({{ }})? | Yes | Yes, but without binding. |
| Returns | A compiled DOM element with bindings. | A plain string after evaluating expressions. |
| Use Case | Dynamically adding AngularJS components/templates to the DOM. | Evaluating dynamic text in non-template contexts (e.g., logs, titles). |
When to Use What?
| Scenario | Use $compile | Use $interpolate |
|---|---|---|
| Dynamically adding AngularJS templates | Yes | No |
Processing directives (ng-model, ng-click) | Yes | No |
| Generating plain text with evaluated expressions | No | Yes |
| Binding scope variables to new elements | Yes | No |
