I am really confused with $compile in angularjs. can anyone help me, What use of $compile in angularjs with an example other then in this documentation. https://docs.angularjs.org/api/ng/service/$compile
Asked
Active
Viewed 1.9k times
2 Answers
13
$compile just compile the text to html..
Here is sample example
angular
.module("myModule", [])
.controller("myController", ['$scope', '$compile', function ($scope, $compile) {
$scope.txt = "<b>SampleTxt</b>";
$scope.submit = function () {
var html = $compile($scope.txt)($scope);
angular.element(document.getElementById("display")).append(html);
}
}]);
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<body ng-app="myModule" >
<div ng-controller="myController">
<textarea ng-model="txt" ></textarea>
<input type="button" value="submit" ng-click="submit()" />
<div id="display"></div>
</div>
</body>

RJV
- 287
- 1
- 7
- 20
-
What if i have text in textbox like {{SampleTxt}}. I mean with curly braces. How can I see the value with curly brace in UI after $compile. – Sunny May 29 '19 at 19:02
-
1Is it possible to invoke `$compile` service from JavaScript from outside AngularJS as a normal function? I can access the scope using `angular.element()` but how I can access the `$compile` service to create HTML element, compile it and insert it or replace the existing one after modifying it? – tarekahf May 31 '21 at 18:51
-6
The first line of this link https://docs.angularjs.org/api/ng/service/$compile already said all about $compile
in simple word it will compile html dom so that it will use for scope of angular js.

Glorfindel
- 21,988
- 13
- 81
- 109

Niketan Raval
- 479
- 2
- 10
-
2
-
1This link may help you http://stackoverflow.com/questions/28854303/using-compile-on-external-template-templateurl-in-angular-directive – Niketan Raval Oct 18 '16 at 06:14