Working with $compile in angularjs

RJV picture RJV · Oct 18, 2016 · Viewed 14.8k times · Source

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

Answer

user6743672 picture user6743672 · Oct 18, 2016

$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>