AngularJS: What and when to use controller, compile, pre-link and post-link?


Compile :

This is the phase where Angular actually compiles your directive. This compile function is called just once for each references to the given directive. For example, say you are using the ng-repeat directive. ng-repeat will have to look up the element it is attached to, extract the html fragment that it is attached to and create a template function.If you have used HandleBars, underscore templates or equivalent, its like compiling their templates to extract out a template function. To this template function you pass data and the return value of that function is the html with the data in the right places.The compilation phase is that step in Angular which returns the template function. This template function in angular is called the linking function.

Linking phase :

The linking phase is where you attach the data ( $scope ) to the linking function and it should return you the linked html. Since the directive also specifies where this html goes or what it changes, it is already good to go. This is the function where you want to make changes to the linked html, i.e the html that already has the data attached to it. In angular if you write code in the linking function its generally the post-link function (by default). It is kind of a callback that gets called after the linking function has linked the data with the template.

Controller :

The controller is a place where you put in some directive specific logic. This logic can go into the linking function as well, but then you would have to put that logic on the scope to make it “shareable”. The problem with that is that you would then be corrupting the scope with your directives stuff which is not really something that is expected. So what is the alternative if two Directives want to talk to each other / co-operate with each other? Ofcourse you could put all that logic into a service and then make both these directives depend on that service but that just brings in one more dependency. The alternative is to provide a Controller for this scope ( usually isolate scope ? ) and then this controller is injected into another directive when that directive “requires” the other one. See tabs and panes on the first page of for an example.

Controller function

Each directive’s controller function is called whenever a new related element is instantiated.

Officially, the controller function is where one:

  • Defines controller logic (methods) that may be shared between controllers.
  • Initiates scope variables.

Again, it is important to remember that if the directive involves an isolated scope, any properties within it that inherit from the parent scope are not yet available.

  • Define controller logic
  • Initiate scope variables
Do not:
  • Inspect child elements (they may not be rendered yet, bound to scope, etc.)

Compile function

Each directive’s compile function is only called once, when Angular bootstraps.

Officially, this is the place to perform (source) template manipulations that do not involve scope or data binding.

Primarily, this is done for optimisation purposes; consider the following markup:

<tr ng-repeat="raw in raws">

The <my-raw> directive will render a particular set of DOM markup. So we can either:

  • Allow ng-repeat to duplicate the source template (<my-raw>), and then modify the markup of each instance template (outside the compile function).
  • Modify the source template to involve the desired markup (in the compile function), and then allow ng-repeat to duplicate it.

If there are 1000 items in the raws collection, the latter option may be faster than the former one.

  • Manipulate markup so it serves as a template to instances (clones).
Do not
  • Attach event handlers.
  • Inspect child elements.
  • Set up observations on attributes.
  • Set up watches on the scope.

Pre-link function

Each directive’s pre-link function is called whenever a new related element is instantiated.

As seen previously in the compilation order section, pre-link functions are called parent-then-child, whereas post-link functions are called child-then-parent.

The pre-link function is rarely used, but can be useful in special scenarios; for example, when a child controller registers itself with the parent controller, but the registration has to be in a parent-then-child fashion (ngModelController does things this way).

Do not:
  • Inspect child elements (they may not be rendered yet, bound to scope, etc.).

Post-link function

When the post-link function is called, all previous steps have taken place – binding, transclusion, etc.

This is typically a place to further manipulate the rendered DOM.

  • Manipulate DOM (rendered, and thus instantiated) elements.
  • Attach event handlers.
  • Inspect child elements.
  • Set up observations on attributes.
  • Set up watches on the scope.

AngularJS: Textarea Auto Resize Directive


Custom directive that resize text area as per user key input or through paste/cut

Over the years I have seen many solutions for this problem, so I have written angualr directive to resolve this issue. I have prefer vertical resize because horizontal resize strikes me as being a mess, due to word-wrap, long lines, and so on, but vertical resize seems to be pretty safe and nice. Please note instead of clientHeight attribute use scrollHeight


  • On key input.
  • With pasted text (right click & ctrl+v).
  • With cut text (right click & ctrl+x).
  • With pre-loaded text.
  • With all textarea’s (multiline textbox’s) site wide.
  • Is w3c validated.

Github Link

Angular Code:

(function () {
  'use strict';

      .module('sampleApp' , [])
      .directive('autoResize', autoResize);

      autoResize.$inject = ['$timeout'];

      function autoResize($timeout) {

          var directive = {
              restrict: 'A',
              link: function autoResizeLink(scope, element, attributes, controller) {

                  element.css({ 'height': 'auto', 'overflow-y': 'hidden' });
                  $timeout(function () {
                      element.css('height', element[0].scrollHeight + 'px');
                  }, 100);

                  element.on('input', function () {
                      element.css({ 'height': 'auto', 'overflow-y': 'hidden' });
                      element.css('height', element[0].scrollHeight + 'px');


          return directive;

Angular HTML Code:

<textarea auto-resize style="resize: none;"></textarea>

Initial State:

capture png

After user input through keystrokes:


After user input through paste:

capturez png

AngularJS: Dynamic Validation Directive


Custom directive that allows text only, number only, special character only or allow everything as per user choice.

Github Link

Angular Code:

(function () {
    'use strict';

        .directive('validate', validate);

    function validate() {
        var directive = {
            restrict: 'EA',
            scope: {
                regex: '=criteria'
            require: 'ngModel',
            controller: validateController,
            link: validateLink

        return directive;

    validateController.$inject = ['$scope'];

    function validateController($scope) {

    function validateLink(scope, element, attrs, ngModelCtrl) {

        element.on('focus', function (e) {

        function validateInput(input) {
            if (input) {
                var regex = new RegExp(scope.regex);
                var newValue = input.replace(regex, '');
                if (newValue !== input) {
                return newValue;
            return undefined;



2016-07-01 14_07_02-mozilla firefox

AngularJS: Prevent changes in parent scope until Save operation is performed in modal


It happens usually when ever you are using ng-repeat in parent page and pass that row data to Modal for editing purpose, any changes made in modal is reflected directly in parent page grid without saving the modal updated data.

2016-02-18 09_01_34-HomePage

As you can see I am changing Course name and it is reflected directly in grid at main page.


What you would need is to clone your model, prior to showing your edit modal, and when a user clicks on closeModal() you would reassign your model to the cloned value.

function DialogController($mdDialog, courseData) {
            var vmPop = this;
            function initPopUp() {
                vmPop.course = [];
                if (courseData)
                    vmPop.course = angular.copy(courseData);

As you can see I am passing courseData to dialog modal controller, before assigning it to modal scope variable (vmPop.course), I am creating a copy of source, which is an object and then assigning it to vmPop.course variable.

Angular Docs for angular.copy

Bootstrap: error retrieving glyphicons-halflings-regular.woff2


One of the most reoccurring issue for the websites using bootstrap theme is “error retrieving glyphicons-halflings-regular.woff2”, Usually it has two occurrence scenarios

  1. We encounter this error from successful AJAX call


2. Some times it is reported as glyphicons-halflings-regular.woff2 not found although it is included in project at exact location



Add below code in your web project web.config file (system.webServer > staticContent >)

      <remove fileExtension=".woff" />
      <mimeMap fileExtension=".woff" mimeType="application/x-font-woff" />
      <remove fileExtension=".woff2" />
      <mimeMap fileExtension=".woff2" mimeType="application/font-woff2" />

GulpJS: Setting up test runner on HTML


Setting up test runner on HTML

  • Use gulp-jasmine-browser in order to execute jasmine tests in a browser using gulp.
  • In order to check output, type following url in browser window: http://localhost:8888/

Pre Install:

    npm install --save-dev  


    npm install --save-dev gulp-jasmine-browser


    var gulp = require('gulp');
    var jasmineBrowser = require('gulp-jasmine-browser');
    var config.files = ['./scripts/lib/angular/angular.js',

    gulp.task('jasmineBrowser', function () {
        return gulp.src(config.files)
          .pipe(jasmineBrowser.server({ port: 8888 }));


    gulp jasmineBrowser

GulpJS: E2E Testing with Protractor


E2E Testing with Protractor

  • Protractor is an end-to-end test framework for AngularJS applications
  • It execute tests against your application running in a real browser, interacting with it as a real life user.
  • Make sure you have updated version of webdriver-manager otherwise execute below command in cmd before executing gulp task
webdriver-manager update --standalone
  • In protractor.config.js file mention file path to the selenium server jar, path of chrome driver and comment out address of a running selenium server before executing gulp task
seleniumServerJar: './node_modules/protractor/selenium/selenium-server-standalone-2.48.2.jar',
chromeDriver: './node_modules/protractor/selenium/chromedriver.exe',
//seleniumAddress: 'http://localhost:4444/wd/hub',
  • Start webdriver-manager in seperate console before executing gulp task
webdriver-manager start
  • __dirname is global object of NodeJS for the name of the directory that the currently executing script resides in

Pre Install:

    npm install --save-dev gulp


    npm install --save-dev gulp-protractor protractor


    var gulp = require('gulp');
    var protractor = require("gulp-protractor").protractor;

    gulp.task('e2e', function (done) {
        gulp.src(__dirname + './protractor_test/')
            configFile: './protractor.config.js',
            args: ['--baseUrl', '']
        .on('error', function (e) { throw e })


    gulp e2e