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

Standard

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 angularjs.org 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.

Do:
  • 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">
    <my-raw></my-raw>
</tr>

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.

Do:
  • 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.

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

AngularJS: Textarea Auto Resize Directive

Standard

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

Features

  • 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';

  angular
      .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:

capture

After user input through paste:

capturez png

AngularJS: Dynamic Validation Directive

Standard

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';

    angular
        .module('sampleApp')
        .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) {
            ngModelCtrl.$parsers.push(validateInput);
        });

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

})();

Output:

2016-07-01 14_07_02-mozilla firefox

AngularJS : Tree Component

Standard

Tree Control is an AngularJS component that cad add siblings, child and remove them. It doesn’t depend on jQuery.

I have tried number of tree control but none is available out in open source community which can assist you to add siblings too. Since I want to control number of childs that can be added to single node. So I came up with my own tree control implementation.

Features

  • Data binding for the tree model
  • Data binding for the selected node in the tree
  • Adding siblings
  • Customize number of childs to be added on a single node(Default: 6)
  • Remove node
  • Recusive controller and Html code
  • Can be customized with CSS

Github Link

Initial State:

2016-07-06 14_28_36-index html

After adding multiple siblings and children:

2016-07-06 14_34_26-index html

Alert if you remove parent with children:

2016-07-06 14_34_43-index html

Alert if number of childs exceeds:

2016-07-06 14_38_26-index html

 

Angular Code:

(function () {
    'use strict';
    
    var app = angular
        .module('sampleApp', []);
    
    app.controller('HomeController', homeController);
 
    homeController.$inject = [];
 
    function homeController() {
        var vm = this;
 
        init();
 
        function init() {
            vm.detailList = [];
            vm.ID = 0;
            vm.parentRecord = {};
            addRootNode();
            vm.AddSibling = AddSibling;
            vm.AddChild = AddChild;
            vm.Delete = Delete;
        }
 
        ////////////////////////////Implementation//////////////////////////////////////
 
        function AddSibling(item) {
            if (item.parentId == 0) {
                addRootNode();
            }
            else {
                findParentRecord(vm.detailList, item.parentId);
                if (vm.parentRecord) {
                    AddChild(vm.parentRecord);
                }
            }
        }
 
        function AddChild(item) {
            var depth = findNodeLevel(vm.detailList, item.ID);
            if (depth < 7) {
                vm.ID = vm.ID + 1;
                item.nodes.push({
                    nodes: [],
                    parentId: item.ID,
                    ID: vm.ID
                });
            }
            else
                alert('maximum level has been reached');
        }
 
        function Delete(item) {
            if (item.nodes.length > 0)
                alert('delete children first');
            else {
                DeleteChild(vm.detailList, item.parentId, item);
            }
        }
 
        ////////////////////////////Helping Function//////////////////////////////////////
 
        function addRootNode() {
            vm.ID = vm.ID + 1;
            vm.detailList.push({
                nodes: [],
                parentId: 0,
                ID: vm.ID
            });
        }
 
        function findParentRecord(arr, parentId) {
            for (var i in arr) {
                if (typeof (arr[i]) == "object") {
                    if (arr[i].ID == parentId) {
                        vm.parentRecord = arr[i];
                        break;
                    }
                    else
                        findParentRecord(arr[i], parentId);
                }
            }
        }
 
        function DeleteChild(arr, parentId, item) {
            for (var i in arr) {
                if (typeof (arr[i]) == "object") {
                    if (arr[i].ID == parentId) {
                        var childrenList = arr[i].nodes;
                        var index = findIndex(childrenList, item.ID);
                        if (index > -1)
                            childrenList.splice(index, 1);
                        break;
                    }
                    else
                        DeleteChild(arr[i], parentId, item);
                }
            }
        }
 
        function findIndex(arr, selectedItemID) {
            for (var i in arr) {
                if (arr[i].ID == selectedItemID)
                    return i;
            }
            return -1;
        }
 
        function findNodeLevel(arr, id) {
            var level = 1;
            findParentRecord(arr, id)
            while (vm.parentRecord.parentId > 0) {
                level = level + 1;
                findParentRecord(arr, vm.parentRecord.parentId);
            }
            return level;
        }
    };
})();

 

Angular HTML Code:

<html>
    <body ng-app="sampleApp" class="ng-cloak">
        
                             
                                                                                                                                               
                            
  •                     
                
            </script>             
                
                
                    
                            
  •                     
                
            </div>