UnderscoreJs with AngularJs

UnderscoreJs is a JavaScript Libraries which have several functions which extend functionality without extending any built-in objects.  It is comparable to features provided by Prototype.js and the Ruby language, but opts for a functional programming design instead of extending object prototypes. For example, Underscore.js each function delegates to the host environment's native forEach implementation when present, or a compatible version when absent. The documentation refers to Underscore.js as "the tie to go along with jQuery's tux, and Backbone.js's suspenders." Underscore.js was created by Jeremy Ashkenas, who is also known for Backbone.js and Coffee Script.

UnderscoreJS have several categories for functions that is-

  • Collections
  • Arrays
  • Objects
  • Function
  • Utility

These function can be directly used on Java Script variables, and provide desired results.

Click here for UnderscoreJs official Site

Now here is a Question : “Why we use UnderscoreJs in our app?”

 “Simple answer is that, by using this we can speed up our coding by avoiding lots of loops and checks.”

 

Lets have a look on AngularJS-

AngularJS (commonly referred to as "Angular" or "Angular.js") is a complete JavaScript-based open source front-end web application framework mainly maintained by Google and by a community of individuals and corporations to address many of the challenges encountered in developing Single Page Application. The framework used for developing cross-platform mobile apps. It aims to simplify both the development and the testing of such applications by providing a framework for client-side model-view-controller (MVC) and model-view-viewmodel (MVVM) architectures, along with components commonly used in rich internet application.

The AngularJS framework works by first reading the HTML page, which has embedded into it additional custom tag attributes. Angular interprets those attributes as directives to bind input or output parts of the page to a model that is represented by standard JavaScript variables. The values of those JavaScript variables can be manually set within the code, or retrieved from static or dynamic JSON resources.

 

Steps For WebApp with AngularJs and UnderscoreJS…

Step 1-Initializing App- first we make an empty web project in Visual Studios. Select Asp.net Web Application after that select empty template.

Step 2- Including Libraries- Now we include library, which we needed in project.

  • Angularjs
  • JQuery
  • Bootstrap
  • Underscorejs
  • Json-formatter

 How we can insert library in our project?

After initializing project we have to insert library, there are several ways, some are following-

  1. Via Manage Nuget Package Manager
  2. Via Node js command prompt
  3. Via Git
  4. Download Script file and put it in the scripts folder

 

In this app I am using fourth method after downloading the .js file put it in script tag in index.html file.

Step 3- Create index.html  file –

Include all libraries in index file.

<head>    <script src="Scripts/jquery-3.1.1.js"></script>    <script src="Scripts/bootstrap.js"></script>    <script src="Scripts/angular.js"></script>    <script src="Scripts/underscore.js"></script>    <script src="Scripts/json-formatter.js"></script>     <link href="Scripts/json-formatter.css" rel="stylesheet" />     <link href="Content/bootstrap.css" rel="stylesheet" /></head>

 

Index file will look like this

Step4- Create app.js-

Create app.js and include it into index.js file script tag.

Now make Angularjs  app and module  as following-

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

 

app.controller('myCtrl', function($scope) {

 

})

 

*remember do not forgot to include 'jsonFormatter’ dependency in to angular app. Because it is third party tool which is in our app.

Step 5- Time to put some dummy data-

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

app.controller('myCtrl', function ($scope) {

    //dummy data for collection example

    $scope.pluckInput = [{ name: 'moe', age: 40 }, { name: 'larry', age: 50 }, { name: 'curly', age: 60 }];

    $scope.pluckOutput = _.pluck($scope.pluckInput, 'name');

    $scope.filterInput = [1, 2, 3, 4, 5, 6];

    $scope.filterOutput = _.filter($scope.filterInput, function (num) { return num % 2 == 0; });

    //dummy data for array

    $scope.firstInput = [5, 4, 3, 2, 1];

    $scope.firstOutput = _.first([5, 4, 3, 2, 1]);

    $scope.flattenInput = [1, [2], [3, [[4]]]];

    $scope.flattenOutput = _.flatten($scope.flattenInput);

    //dummy data for object functions

    $scope.keysInput = { one: 1, two: 2, three: 3 };

    $scope.keysOutput = _.values({ one: 1, two: 2, three: 3 });

    $scope.invertInput = { Moe: "Moses", Larry: "Louis", Curly: "Jerome" };

    $scope.invertOutput = _.invert({ Moe: "Moses", Larry: "Louis", Curly: "Jerome" });

 

})

in app.js  put following code as following-

I have created three section for Underscore.js demo-

 

  • Collection Functions Demo
  • Array Functions Demo
  • Object Functions Demo

Collection Functions Demo-

For this section I have selected two functions:

  • pluck
  • filter

pluck_.pluck(list, propertyName) :

A convenient version of what is perhaps the most common use-case for map: extracting a list of property values.

If we want to extract all values for one property then we use this function.

Example:

 $scope.pluckInput = [{ name: 'moe', age: 40 }, { name: 'larry', age: 50 }, { name: 'curly', age: 60 }]; $scope.pluckOutput = _.pluck($scope.pluckInput, 'name');

value in $scope.pluckOutput = ["moe", "larry", "curly"]

 

filter_.filter(list, predicate, [context]) :

Looks through each value in the list, returning an array of all the values that pass a truth test (predicate).

Example: In this example if we have taken a function which return even number , we can put any function.

 $scope.filterInput = [1, 2, 3, 4, 5, 6];

 $scope.filterOutput = _.filter($scope.filterInput, function (num) { return num % 2 == 0; });

value in  $scope.filterOutput = [2,4,6]

 

Array Functions Demo

For this section I have selected two functions:

  • first
  • flatten

 

first_.first(array, [n]) :

 

Returns the first element of an array. Passing n will return the first n elements of the array.

Example: in this example underscorejs function will return first element of this array

$scope.firstInput = [5, 4, 3, 2, 1];

$scope.firstOutput = _.first([5, 4, 3, 2, 1]);

Value in $scope.firstOutput = 5

 

flatten_.flatten(array, [shallow]) :

 

Flattens a nested array (the nesting can be to any depth). If you pass shallow, the array will only be flattened a single level.

Example:  in this example three level array Array is taken after using flatten function of UnderscoreJS we will find single level array.

$scope.flattenInput = [1, [2], [3, [[4]]]];$scope.flattenOutput = _.flatten($scope.flattenInput);

 Value inside $scope.flattenOutput = [1,2,3,4]

Object Functions Demo-

 

For this section I have selected two functions:

  • keys
  • invert

keys_.keys(object) :

Retrieve all the names of the object's own enumerable properties.

Example: this function will return the property name associated with in object.

$scope.keysInput = { one: 1, two: 2, three: 3 };$scope.keysOutput = _.values({ one: 1, two: 2, three: 3 });

 value in $scope.keysOutput= ["one", "two", "three"]

 

invert_.invert(object):

Returns a copy of the object where the keys have become the values and the values the keys. For this to work, all of your object's values should be unique and string serializable.

Example:

$scope.invertInput = { Moe: "Moses", Larry: "Louis", Curly: "Jerome" };$scope.invertOutput = _.invert({ Moe: "Moses", Larry: "Louis", Curly: "Jerome" });Value in $scope.invertOutput = {Moses: "Moe", Louis: "Larry", Jerome: "Curly"}; 

In index.html put this code-

After completing this press ctrl+f5. Our app will look like this.

This is how we can use UnderscoreJs inside the AngularJS App.