Blogger news

Blogger templates

Saturday, July 26, 2014

$compile service in AngularJS

If you are new to AngularJS I would prefer to go through my introduction blog on AngularJS before read this article.
$compile service is used heavily internally by Angular. When ever page is loaded Angular uses $compile
 service to look through pages for directives and process them. We can also use compile service ourself, typically we are using it inside directives (Wait for my blog on directives). 

I will explain compile service with a small example. 
As usual first I created a module,

var app = angular.module('app', []);

Next Controller,
app.controller('CompilerServiceController',function($scope, $compile){

    app.controller('CompilerServiceController', function ($scope, $compile) {

    $scope.appendDivToElement = function (htmlMarkUp) {
        return $compile(htmlMarkUp)($scope).appendTo(angular.element('#appendMarkUp'));


In controller what we are trying to do is to compile the htmlMarkup that we are sending to view. After compiling  htmlMarkUp we are appending that to a div with id 'appendMarkUP'. angular.element('#id') is the angular way to find markups. I will explain more after add our view
<!DOCTYPE html>
<html ng-app="app">
<head lang="en">
    <meta charset="UTF-8">
    <div ng-controller="CompilerServiceController" style="padding:20px;">

        <div id="appendMarkUp"></div>
        <br />
        name:<input type="text" ng-model="name" /><br />
        markup: <input type="text" ng-model="htmlMarkUp" /><br />
        <button class="btn" ng-click="appendDivToElement(htmlMarkUp)">Append</button>

    <script src="../lib/jquery.min.js"></script>
    <script src="../AngularScripts/angular.min.js"></script>
    <script src="../AngularScripts/angular-resources.js"></script>
    <script src="../Modules/app.js"></script>
    <script src="../Controllers/CompilerServiceController.js"></script>


As you can see we have two text boxes here one to enter a name and other to enter htmlMarkUp. On click of htmlMarkUp text box we are calling the function 'appendDivToElement' by passing the html mark-up we entered and this function is in our controller. I will first show the output,

As you can see here we entered the name 'ThunderCats' and a mark-up for button in next text box but value of button is name property which is the model of first textbox. When we click 'Append' button $compile service compiled the plain html text we entered to proper html out, here it is a button. 
Hope you are clear what $compile service will do.


No comments:

Post a Comment