Underscore.JS: Access local variables and function inside each function of UnderscoreJS in Typescript

Standard

While using AngularJS with Typescript, I witnessed the scenario, where my function is accessing variables and functions defined in controller constructor, to make life easy for some collection manipulation, I used underscoreJS helper functions, _.each

_.each(data, function(item : any) {
     item.name = this.formatName(item);
});

Everything was on track, except I was unable to access local variables and functions(this.formatName) defined in the angular controller in underscoreJS _.each, I was getting an undefined error for this.formatName method inside _.each.

Solution:

As you are aware of the fact that ‘this‘ keyword behaves differently in JavaScript compared to other languages. For Typescript, ‘this‘ keyword refers to the current instance of the class. In JavaScript, the value of ‘this‘ is determined mostly by the invocation context of the function and where it is called. (Read this reference)

  1. In order to resolve this problem, inject ‘this‘ as context by setting it up as the third parameter to _.each helper function
_.each(data, function(item : any) {
     item.name = this.formatName(item);
}, this);

2. There is one more solution too by saving the context in temporary variable before consuming ‘this’ in _.each

public testFunction() : void {
  var context = this;
  _.each(data, function(item : any) {
      item.name = context.formatName(item);
  });
}

 

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.

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: Prevent changes in parent scope until Save operation is performed in modal

Standard

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.

Solution:

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;
            initPopUp();
 
            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

Standard

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

Hk5i5

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

 

Solution:

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

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

GulpJS: Setting up test runner on HTML

Standard

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  

Install:

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

Code:

    var gulp = require('gulp');
    var jasmineBrowser = require('gulp-jasmine-browser');
    var config.files = ['./scripts/lib/angular/angular.js',
        './scripts/lib/angular/angular-mocks.js',
        './scripts/app/myService.services.js',
        './scripts/app/myService.services-spec.js',];

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

Execute:

    gulp jasmineBrowser