CSS Tooltip, without JavaScript or Jquery

In this article I’m going to explore how to Create css tooltip, without using JavaScript or JQuery plugins.

css tooltip


Tooltips are great artifact to complement/enrich the user experience providing hint and more information to the user. There are a lots of JavaScript plugins that provides this functionality, but if you don’t feel like adding that weight to your site, adding more files and more JavaScript code, we can take care of it just using plain CSS.
As an alternative we can use the HTML title attribute to effectively accomplish the same solution, but you can’t style the tooltip to your liking.
Sometimes I prefer to use CSS alternatives to common JavaScript interactions when I’m developing specially when I’m developing prototypes. There are some projects where downloading a plugin or creating a new file for a few lines of code seems like overkill.

Here is a working example:

Hover over this


Creating a Css Tooltip

To create our tooltip just using css, we are going to take advantage of the ::before and ::after selector, we are going to use the ::before for the tooltip body and the ::after for the littler arrow. We are going to set the Tooltip content with data-tooltip parameter of the html element.

 <span class="tooltip-toggle" data-tooltip="Sample text for your tooltip!">
     Hover over this


Definition and Usage.

::after selector inserts something after the content of each selected element(s).
You can use the content property to specify the content to insert. This property can be combined with the attr() attribute to get the text from an html atribute.
::before selector inserts something before the content.

.tooltip-toggle::before {
  position: absolute;
  top: -80px;
  left: -80px;
  background-color: green;
  border-radius: 5px;
  color: #fff;
  content: attr(data-tooltip);
  padding: 1rem;
  text-transform: none;
  -webkit-transition: all 0.5s ease;
  transition: all 0.5s ease;
  width: 160px;

.tooltip-toggle::after {
  position: absolute;
  top: -12px;
  left: 9px;
  border-left: 5px solid transparent;
  border-right: 5px solid transparent;
  border-top: 5px solid green;
  content: " ";
  font-size: 0;
  line-height: 0;
  margin-left: -5px;
  width: 0;

With the :hover we can show/hide the tooltip as a transition:

.tooltip-toggle:hover::after {
  opacity: 1;
  -webkit-transition: all 0.75s ease;
  transition: all 0.75s ease;

.tooltip-toggle::after {
  color: #efefef;
  font-family: monospace;
  font-size: 16px;
  opacity: 0;
  pointer-events: none;
  text-align: center;

Here is the full code example of the css tooltip:

Interview Question

You can also use this article as reference to create css interview questions for a seasoned front-end developer, to validate the deep experience on using, formating the ::before and ::after elements.

Prevent angular executing controller twice (Mini-Challenge 11)

Prevent angular executing controller twice (Mini-Challenge 11)

Prevent angular executing controller twice

AngularJs Mini-Challenges is a growing collection of “Challenges” about the most quirky parts of the AngularJs framework. It encourage you to find and fix common mistakes and subtle bugs, as well as performance issues and bad practices, that non-expert AngularJs programmers may encounter on their endeavours into the depths of the framework.

AngularJs Mini-Challenges does not aim to teach you AngularJs. Former knowledge of the Framework is strongly recommended in order to understand the topics covered in this Challenges. In order to learn the basics of the Framework, please head over to this excellent guide https://www.ng-book.com/


The Challenge:

We have an Angularjs application. For this challenge we are going to show only the fragment of code necessary to solve the challenge. Below we have the controller, the view and the router. when you navigate to the #/dashboard page you noticed that the controller is executed twice by placing a breakpoint in your browser console. This makes the analyticsServices.save() method to execute twice duplicating the data in your database. What you would do to prevent angular executing controller twice?

This is the controller

function MyController($scope, userServices, analyticsServices) {

    userServices.get({ id: $scope.currentUserId },
        function(user) {

This is a fragment of the code in the view:

<!-- dashboard.html -->
<div ng-controller="MyController">

<!-- html content -->


This is the of the router

 .when('/dashboard', {
            templateUrl: '/app/dashboard/dashboard.html',
            controller: 'MyController',
            controllerAs: 'ctr',
            title: 'Dashboard'


Having the controller defined in the controller property in the router and also defined in the ng-controller in the view, this digested the controller twice. Removing the ng-controller directive from the HTML view can resolve the issue. Alternatively, you can remove the controller: property from the routing directive.

Hope this was helpful, please feel free to leave your comments, share other scenarios, or improve this solution! :)

How to avoid js files cache script bundle with razor

It happened to me, that I was working on an ASP.NET MVC Razor with AngularJs application, and every time that the team make a change in the AngularJs files and deploy to Production, the users start complaining about unresolved issues in the application. Those issues were because of the browser cache the JavaScript files in the client side. So in this article, I’ll try to find an optimal solution to this problem, meaning that the javascript bundle should avoid cache when a new version of the application is deployed to production.
bundle cache

Avoiding browser cache:

We have to consider that one of the most popular techniques to avoid browsers cache with javascript files is to add a variable at the end of the file name, like this: src=”/app/app.js?nocache=12365434576″.

  <script type="text/javascript" src="/app/app.js?nocache=12365434576"></script>

Now this resolve the issue partially since 12365434576 it’s going to be a random number that always going to avoid the cache, and we don’t want that, we want to avoid cache only when a new version is deployed, for a better performance. So what we need to do is, instead of set the nocache var to a random number we are going to user the version of the application, like this:

Bundle Code:

We had a code like this to compose the bundle in App_Start/BoundleConfig.cs

 private static void AddAppBundles(BundleCollection bundles)
            var path = "admin";
            var scriptBundle = new ScriptBundle("~/js/app");
            var FullPath = HttpContext.Current.Server.MapPath(string.Format("~/{0}", path));
            if (Directory.Exists(FullPath))
                    // Order matters
                    string.Format("~/{0}/app.module.js", path),
                    string.Format("~/{0}/app.core.module.js", path)

                    .IncludeDirectory(string.Format("~/{0}", path), "*.module.js", true)
                    .IncludeDirectory(string.Format("~/{0}", path), "*.js", true);

With the code above we can include all the javascript files found in “path” variable in our _Layout.cshtml page, with this code:


The code is going to render something like this:

  <script type="text/javascript" src="/app/app.js"></script>
<script type="text/javascript" src="/app/config.js"></script>
<script type="text/javascript" src="/app/dashboard/dashboard.module.js"></script>
<script type="text/javascript" src="/app/layout/layout.module.js"></script>
<script type="text/javascript" src="/app/blocks/apiendpoint.config.js"></script>
<script type="text/javascript" src="/app/blocks/apiendpoint.provider.js"></script>

The question here is how we can render something like this src=”/app/app.js?nocache=1.28.16145.10″, when we render the bundle in razor.
We are going to use @Scripts.RenderFormat.


    string version = typeof(yourProjectNamespace.WebApiApplication).Assembly.GetName().Version.ToString();
    <!--app scripts.-->
    @Scripts.RenderFormat("<script type=\"text/javascript\" src=\"{0}?nocache="+ version +"\"></script>", "~/js/app")

This is an example of the result rendered:

  <script type="text/javascript" src="/app/app.js?nocache=1.28.16145.10"></script>
<script type="text/javascript" src="/app/config.js?nocache=1.28.16145.10"></script>
<script type="text/javascript" src="/app/dashboard/dashboard.module.js?nocache=1.28.16145.10"></script>
<script type="text/javascript" src="/app/layout/layout.module.js?nocache=1.28.16145.10"></script>
<script type="text/javascript" src="/app/blocks/apiendpoint.config.js?nocache=1.28.16145.10"></script>
<script type="text/javascript" src="/app/blocks/apiendpoint.provider.js?nocache=1.28.16145.10"></script>

Hope this was helpful. :)

State Management in ASP.Net

In this article I’ll try to cover the different techniques session state management in ASP.Net applications. With this we are going to be able to determine the best approach for our solution when we manage the session states in ASP.Net applications.
session state management

These are the session state management options in Asp.net

  • Off
  • StateServer
  • InProc
  • SQLServer
  • Cookies
  • Query String
  • Custom

Fot Off|StateServer|InProc|SQLServer, we will need to specify the session state tag in the web.config. This is a template code:

<sessionState mode="Off|StateServer|InProc|SQLServer"
              timeout="number of minutes"
              sqlConnectionString="sql connection string"
              stateNetworkTimeout="number of seconds"/>

Off Mode

Off mode, which disables session state.

StateServer Session State mode

StateServer Session State mode, which stores session state in a separate process called the ASP.NET state service. This ensures that session state is preserved if the Web application is restarted and also makes session state available to multiple Web servers in a Web farm. StateServer session runs as a Windows service and would help to minimize database traffic.

    <sessionState mode="StateServer"

InProc Session State

InProc Session State, this mode stores session state with the ASP.NET worker process (in memory on the Web server). It is not valid in a web farm configuration.

      <sessionState mode="InProc"

SqlServer Session State

SqlServer Session State. stores session state in a SQL Server database. This ensures that session state is preserved if the Web application is restarted and also makes session state available to multiple Web servers in a Web farm. Although, It does support a web farm configuration, you should not use this if you want to minimize database traffic.

    <sessionState mode="SQLServer"
      sqlConnectionString="Integrated Security=SSPI;data 
        source=SampleSqlServer;" />

Cookie State mode

Cookie State mode. Cookies are stored on the client, so the application would not be able to keep the state if they switched to a different device or a different browser. Also the user needs to have the cookies enabled in their browser

Query String

Query String It can be used for passing limited state information across request boundaries, this solution would not be able to keep the state if they switched to a different device. This solution will work even if the user have disabled the cookies in the browser.

Custom mode

Custom mode, which enables you to specify a custom storage provider.

    <add name="OdbcSessionServices" 
      connectionString="DSN=SessionState;" />

        <add name="OdbcSessionProvider"
          writeExceptionsToEventLog="false" />

These are the options we have in Asp.net to manage the session state in an application. Hope this was helpful.

ASP.NET MVC Routers common questions

I’m doing this article as a self remainder of how to declare routers in ASP.NET MVC I will try to answer the most common questions about ASP.NET MVC Routers that I was able to find on internet. Hopefully this might help you as well. Routers

When you create a MVC application with Visual Studio, and you go to the RouteConfig.cs file this is the default code generate by the template:

                name: "Default",
                url: "{controller}/{action}/{id}",
                defaults: new { controller = "Home", 
                                action = "Index", 
                                id = UrlParameter.Optional },
                constraints: new {id = @"\d+"}

Most common questions about routers:

“Why do we use route.IgnoreRoute?”
This will tells the routing engine to ignore any requests that match the provided pattern “{resource}.axd/{*pathInfo}”. In this case to ignore any requests to axd resources.

“Why the parameters in {} ?”
The {} indicates that the delimited string is a variable, it can anything. In the ignore route this is used so that any .axd requests are matched.

Why map MapRoute has First parameter “Default”
The first parameter is the route name. This can be used when referring to routes by name. It can be null

  "Default", //Default Route
  "{controller}/{action}/{id}", // URL with parameters
   new { controller = "Home", action = "Index", id = UrlParameter.Optional } 

  "Feedback", // Custom Route name
   new { controller = "Home", action = "Feedback" }

//Then you can call it like this:

What is the Second Parameter-“{controller}/{action}/{id}” for?
This is the pattern that is matched. In this case it is setting up the default route which is a url formed by the controller name, action name and an optional id. The url http://yoursite.com/Foo/Bar would call the Bar method on the Foo controller. Changing the url to http://mysite.com/Foo/Bar/1 would pass a parameter with the identifier id and value 1.

What is the third parameter?
The third parameter supplies defaults. In the case of the default route the default controller name is Home and the default action is Index. The outcome of this is that a request to http://yoursite.com would call the Index method on the Home controller. The id part of the route is specified as being optional with UrlParameter.Optional.

What is the fourth parameter?
The fourth parameter is for constraints, you can use regular expressions, in this example in particular this expression “\d+” match strings that are sequences of one or more digits (0-9).

How to create a custom Routers Constraint?
For this example we are going to create a Guid constraing, we have to create a class that inherit from IRouteConstraint and implement it:
routers implement interface
This is the code:

public class GuidConstraint : IRouteConstraint {

public bool Match(HttpContextBase httpContext, Route route, string parameterName, 
                  RouteValueDictionary values, RouteDirection routeDirection)
    if (values.ContainsKey(parameterName))
        string stringValue = values[parameterName] as string;
        if (!string.IsNullOrEmpty(stringValue))
            Guid guidValue;
            return Guid.TryParse(stringValue, out guidValue) && (guidValue != Guid.Empty);
    return false;

You can use it in the route like this:

routes.MapRoute("doubleGuid", "{controller}/{action}/{guid1}", 
                 new { controller = "YourController", action = "YourAction" }, 
                 new { guid1 = new GuidConstraint() });

Why we use new?
The new keyword is creating/instanciating an object using the object initializer syntax that was introduced in version 3 of the .Net framework.

Difference between “MapHttpRoute” and “MapRoute”?
ultimately both operate on the same underlying ASP.NET route table, the difference is that MapRoute is used for when the application is hosted in ASP.NET. MapHttpRoute is used for Web Apis for when hosting outside of ASP.NET, Web API wouldn’t have to rely on System.Web.
Web API is not sitting on top of MVC, Web Forms, or, for that matter ASP.NET at all. It can be hosted within web context (ASP.NET) but can also be self hosted in a Console app, WPF, etc.

The major advantage of using routing is that it creates a convention for your Urls. If you created a new controller called Account and action methods called Index and Review then the methods would be available at /Account and Account/Review respectively.

Other resources:

How to create a custom controller factory ASP.Net MVC

I was reading about “Control application behavior by using MVC extensibility points” which is one of the objectives for the 70-486 Microsoft certification, and it was not clear to me, the explanation provided. So I decided to write about it to make clear for me, and I hope this help you as well.

An ASP.NET MVC application contains the following class:

public class HomeController: Controller
   public HomeController(Ilogger logger)//notice the parameter in the constructor


This throw an error with the DefaultControllerFactory see image below.
Dependency injection controller error

The application won’t be able to load the Home controller because it have a parameter. You need to ensure that Home Controller can be instantiated by the MVC framework. In order to accomplish this we are going to use dependency injection.

The solution is to create a custom controller factory.

It calls the default constructor of that class. To have the MVC framework create controller class instances for constructors that have parameters, you must use a custom controller factory. To accomplish this, you create a class that implements IControllerFactory and implement its methods. You then call the SetControllerFactory method of the ControllerBuilder class to an instance of your custom controller factory class.

Create the CustomControllerFactory that inherit from IControllerFactory:

 public class CustomControllerFactory : IControllerFactory

        public CustomControllerFactory()

        public IController CreateController(System.Web.Routing.RequestContext requestContext, string controllerName)
             ILogger logger = new DefaultLogger();
        var controller = new HomeController(logger);
        return controller;

        public System.Web.SessionState.SessionStateBehavior GetControllerSessionBehavior(System.Web.Routing.RequestContext requestContext, string controllerName)
             return SessionStateBehavior.Default;

        public void ReleaseController(IController controller)
            var disposable = controller as IDisposable;
            if (disposable != null)


You can implement the CreateController() method with a more generic way, using reflection.

public class CustomControllerFactory : IControllerFactory
    private readonly string _controllerNamespace;
    public CustomControllerFactory(string controllerNamespace)
        _controllerNamespace = controllerNamespace;
    public IController CreateController(System.Web.Routing.RequestContext requestContext, string controllerName)
        ILogger logger = new DefaultLogger();
        Type controllerType = Type.GetType(string.Concat(_controllerNamespace, ".", controllerName, "Controller"));
        IController controller = Activator.CreateInstance(controllerType, new[] { logger }) as Controller;
        return controller;

Set your controller factory in Application_Start by using SetControllerFactory method:

 protected void Application_Start()


This could be one of the objective of the Microsoft certification exam 70-486, more specific for “Develop the user experience”, sub-objective “Control application behavior by using MVC extensibility points”.
Hope this helped you to understand how to do dependency injection in controllers with MVC.

External references:

Arrays as Multipurpose Data Structures in JavaScript

In JavaScript the Array object is a very powerful data structure with it you can “simulate” other data structures, like Queues, Stacks, List, etc.

There is a list with some of the most important methods of the array object in JavaScript, we going to use them to create/simulate our data structures, you can see example of these methods in action, below.

Array.push(value1, value2, value3,…) – Add one or more Elements to the end of the array. This method will return the new length of it. You can specify multiple comma separated values.
Array.pop() – Removes the last element from an array and returns it.
Array.unshift(value1, value2, value3,…) – Add one or more elements to the beginning of the array. This method will return the new array length. You can specify multiple comma separated values.
Array.shift() – Removes the first element from an array and returns it.
Array.splice(splice(start, deleteCount[, item1[, item2[, …]]])) – The splice() method changes the content of an array by removing existing elements and/or adding new elements.

Data Structures array

Other useful methods.

We are not going to use this methods to create the data structures showed in this post, but it might be handy.

Array.reverse() – Reverses the order by position (the first element becomes the last and the last one becomes the first, etc).

var arr = ['a', 'b', 'c'];
console.log(arr); //this will display ["c", "b", "a"]

Array.sort([compareFunction]) – Allows you to sort an array by specifying a compare function which has access to each value in the array you want to sort.

var arr = ['d', 'e', 'b', 'c', 'a'];
arr.sort(function(a, b){
  if (a < b) { return -1; } if (a > b){ return 1; }
  // a must be equal to b
  return 0;
console.log(arr); //this will display ["a", "b", "c", "d", "e"]
//Note: for this simple sort you can do arr.sort(), an you'll obtain the same result.

Array.join(separator) – This method takes one or more items in the array and returns a string of values joined by their separator. If you don’t specify a separator, the default is a comma.

var arr = ['a', 'b', 'c'];
var str = arr.join('-');
console.log(str); //this will display "c-b-a"

Array.indexOf(value) – This method allows you to find the first occurrence of the specified value, or –1 if not found.

var arr = ['a', 'b', 'c'];
if(arr.indexOf("a") > -1)
console.log('found "a" in arr');


Data Structures

  • Arrays used as Queue

  • Arrays used as Stack

  • Arrays used as List


Arrays as Queue:

A queue follows the First-In First-Out (FIFO) paradigm: the first item added will be the first item removed. An array can be turned into a queue by using the push() and shift() methods. push() inserts the passed argument at the end of the array, and shift() removes and returns the first item, consider the following example:

function Queue(length) {
    var ret = [];

    ret.enqueue = function(a) {
        if(ret.length == length){
        return Array.prototype.push.apply(this, arguments);
    ret.dequeue = function(){
        return Array.prototype.shift.apply(this);
    return ret;

var aux = Queue(3);
console.log(aux); // should contain dog, duc, worm

Arrays used as Stack.

A stack follows the Last-In First-Out (LIFO) paradigm: an item added last will be removed first. The Array class has 2 methods that provide stack functionality. they are push() and pop(). push() appends an item to the end of the array, and pop() removes and returns the last item in the array
push(data) adds data.

pop() removes the most recently added data.

function Stack() {
    var ret = [];

    ret.push = function(a) {
        return Array.prototype.push.apply(this, arguments);
    ret.pop = function(){
        return Array.prototype.pop.apply(this);

    return ret;

var stack= Stack();

Arrays used as List.

A List a collection of unsorted elements, where you can add or remove elements.

function List() {
    var ret = [];
    ret.add = function(element) {
        return Array.prototype.push.apply(this, arguments);
    ret.remove = function(element){
        return Array.prototype.slice.apply(this, ret.splice(ret.indexOf(element), 1));
    return ret;

var aux = List();

Wrapping up:

As you can see the those three data structures queue, stack and list are simple arrays wrapped in a function to rename the methods used to add or remove elements from the collections with more semantic names. If you have any enhancement or any subjection please don’t hesitate to share with us.

References to learn more:

developer.mozilla.org – Arrays

IQueryable VS IEnumerable in C#

As C# developers we use IEnumerable and IQueryable for data manipulation almost all the time in our application projects, and for me, sometimes is confusing when to use one or another. So I searched in internet and created the table bellow so if I forget I can quickly come to this post and review the differences so I can get the most of each and make sure I use it correctly.

IQueryable IEnumerable

IEnumerable IQueryable
Namespace. System.Collections System.Linq
Derives from. No base interface. Derives from IEnumerable.
Deferred Execution. Supported. Supported.
Lazy Loading. Not Supported. Suported.
Suitable for. LINQ to Object and LINQ to XML queries. LINQ to SQL queries.
Custom Query. Doesn’t supports. Supports using CreateQuery and Execute methods.
Other characteristics. It is a read only collection.
It iterates only in forward direction.
It works with collection in local memory.
It does not support adding, removing objects on collection.
It provides enumerator to iterate collection in forward direction.
It implements IEnumerable,so the results can be iterated using foreach.
It is best suited to query external data sources,(like remote database, service) collections.
It works with queryable data provider.
It creates query using an Expression Tree.
It is used to query a queryable data source.
When to use… Working with the read only collection.
Need to read the objects in forward direction only.
Not concerned about thread safety.
Want to iterate the collection’s objects using foreach.
Working with the queryable datasource.
Need to apply filter on data at the datasource.
Need to apply paging , composition.
Working with external data source.
Needs to load data in deferred way.
Need to use foreach to iterate collection.

IEnumerable Example:

DataContext ctx = new DataContext ();
IEnumerable<People> collection = ctx.People.Where(p => p.Name.StartsWith("j"));
collection = collection.Take<People>(20); 

Generated SQL statements of above query will be :

 SELECT [t0].[ID], [t0].[Name], [t0].[Salary] FROM [People] AS [t0]
WHERE [t0].[Name] LIKE @p0

Notice that in this query “top 20” is missing since IEnumerable place all the records in memory and filters on client side.

IQeryable Example:

 DataContext ctx = new DataContext ();
IQueryable<People> collection = ctx.People.Where(p => p.Name.StartsWith("j"));
collection = collection.Take<People>(20); 

Generated SQL statements of above query will be :

SELECT TOP 20 [t0].[ID], [t0].[Name], [t0].[Salary] FROM [People] AS [t0]
WHERE [t0].[Name] LIKE @p0

Notice that in this query “top 20” is exist, since IQueryable executes query in SQL server with all filters, and put in memory the result already filtered.

Official documentation for IQueryable and IEnumerable:


Closure in JavaScript through examples

javascript closureWhat is Closure?

A Closure is a named or anonymous function defined within the context of an object or any other function, which preserves and access to the context where it was declared.

To understand closure, it requires you to be familiar with basic JavaScript concepts, such as scope of variables and functions.

A closure is a named or anonymous function:
javascript closure
This is not a closure:

//Named function
function greetings() { //this is not a closure function.
    return ‘Howdy’;

//anonimous function
var greetings2 = function () { //this is not a closure function.
    return ‘Hello’;

greetings(); //Shows Howdy.
greetings2(); //Shows Hello.

Basically a closure function is a function that can access to the variables declared in the outer context, including global variables.

Closures in action.

Here is an example that will help you recognize when you need to use a Closure.

How to do it correctly.

Suppose you want to use a variable to count and want to create a function to increment the count variable.

var counter = 0;
function increase() {
    counter += 1;  // increment its current value.


 // The counter is now equal to 3.

Here we have a solution, but has flaws; the counter variable is global, any script on the page would have access to it and could change it without calling the increase function .

We need to make sure that the counter variable is only modified by the increase function.

Therefore, move the definition of the variable inside the function, so no one can modify it without calling the function increase:

function increase() {
    var counter = 0;
    counter += 1; // increment its current value.


// We expect the value of the count variable is 3, but it will be 1.

Now the counter variable is not accessible from the outside (now is protected), but this wong work properly because every time you call the function it will define the variable account.

We need to create an internal function to solve this:

var increase = (function() {
    var counter = 0;
    return function () {
        return counter += 1;
})(); //* IIFE Auto-invoked function.


// The counter is now equal to 3.

*IIFE Immediately Invoked Function Expression (see Encapsulation in JavaScript).

A common mistake

Here’s an example of misuse of Closure function. Suppose we have the following code:

function count() {
     var i;
     for (i = 1; i <= 3; i ++) {
         setTimeout (function () {
             console.log ('The count value is '+ i);
         }, 1000); // 1000 milliseconds = 1 second

And this is how you can solve it:

function count() {
     var i;
     function display(j) {
         return function () {
             console.log ('The counter value is ' + j);

     for (i = 1; i <= 3; i ++) {
         setTimeout (display(i), 1000);


I’m not going to explain in detail how this is solved, I’ll leave it to you, if you understand what happened then you understand JavaScript closure. 😉

Other references:


AngularJs: Notes for a better performance

Performance notes for AngularJs 1.x:

angularjs performanceThis is a compilation of few tips that you can use to improve the performance of your Angular applications. I got some of this techniques from internet and others from my personal experience when working with large enterprise AngularJs applications.

Avoid $watch

-Try to avoid as much as possible the use of $watch because Angular uses dirty checking to keep track of all the changes in app. This means it will have to go through the collection of watcher to check if they need to be updated (call the digest cycle). If one of the watcher is relied upon by another watcher, Angular would have to re-run the digest cycle again, to make sure that all of the changes has propagated. It will continue to do so, until all of the watchers have been updated and app has stabilized.

-One-time binding syntax:

In newer versions of Angular (v1.3.0-beta.10+), use the one-time binding syntax {{ ::value }} where it makes sense

//try to avoid
<div>{{ vm.title }}</div>

// recommended
<hdiv>{{ ::vm.title }}</div>

Binding once removes the watcher from the scope’s $$watchers array after the undefined variable becomes resolved, thus improving performance in each dirty-check. Make sure you use this only when you don’t need to update the value through the application life cycle.

-Debounce the ng-model

If you know there is going to be a lot of changes coming from an ng-model, you can de-bounce the input.
For example if you have a search input like Google, you can de-bounce it by setting the following ng-model option: ng-model-options=”{ debounce: 250 }.
This will ensure that the digest cycle due to the changes in this input model will get triggered no more than once per 250ms. Also you can make the model updates when an event happen, e.g. on blur: ng-model-options=”{ updateOn: ‘blur’ }”

-Limit DOM filters

Filters are really simple to use, we insert a pipe, the filter name and we’re done. However, Angular runs every single filter twice per $digest cycle once something has changed. This is some pretty heavy lifting. The first run is from the $$watchers detecting any changes, the second run is to see if there are further changes that need updated values.
Here’s an example of a DOM filter, these are the slowest type of filter, preprocessing our data would be much faster. If you can, avoid the inline filter syntax.

{{ filter_expression | filter : expression : comparator }}

Angular includes a $filter provider, which you can use to run filters in your JavaScript before parsing into the DOM. This will preprocess our data before sending it to the View, which avoids the step of parsing the DOM.

$filter('filter')(array, expression, comparator);


-Avoid JavaScript expensive operations

The most expensive operation in JavaScript is add or remove elements from the DOM, maybe you wont notice a performance issue when you add or remove a few element, but it could be a problem if you have to remove or insert thousands in a large application.

-How to detect bad performance in AngularJs:

  • Benchmark functions using console.time. You can use the console.time to have a rough idea of how long a function takes to execute the code, you can read more about console.time here.
  • Use Batarang extension to detect performance issues, also you can us it to debug your Angular app in general.



Tips and good practices in general:

  • Design your directives with Angular in mind, try to avoid as much as possible the use of JQuery.
  • Everything related to DOM manipulation should be in a directive.
  • Avoid use the controller to do business logic, the purpose of controllers is binding data to your view. They should not contain any logic and merely communicate with your services.
  • Use services and /or factories to do business logic and call the Apis.
  • If possible, you should consider fetching your data before your view gets initialized. By doing so, you can ensure that necessary data is available as soon as the user get’s the page, you could accomplish that by using resolve in your routingProvider. See this article.
  • Extend directives by using Directive Controllers, you can place methods and properties into a directive-controller, and access that same controller from other directives. You can even override methods and properties through this relationship.
  • Don’t wrap element inside of $(). All AngularJS elements are already jq-objects.
  • Don’t do if (!$scope.$$phase) $scope.$apply(), it means your $scope.$apply() isn’t high enough in the call stack. Best Practice to run the cycle digest
  • Don’t create a new plugin without trying to discover, fork and pull request existing plugins first.