Category Archives: AngularJS

WHEN DO WE USE $APPLY() IN ANGULAR? IS IT A GOOD PRACTICE TO USE?

When do we use $apply() in Angular? Is it a good practice to use?

$apply() is used to execute an expression in angular from outside of the angular framework. (For example from browser DOM events, setTimeout, XHR or third party libraries). Because we are calling into the angular framework we need to perform proper scope life cycle of exception handling, executing watches

We use it very rarely. AngularJS actually calls almost all of your code within an $apply call. travel Events like ng-click, controller initialization, $http callbacks are all wrapped in $scope.$apply(). So you don’t need to call it yourself, in fact you can’t. Calling $apply inside $apply will throw an error.

COMMON MISTAKES ANGULAR JS DEVELOPERS MAKE

Common Mistakes Angular JS Developers make

Angular JS is a Javascript structural framework for dynamic web pages that enables usage of HTML as a template language and allows the extension of HTML’s syntax in order to achieve the lucid and concise expression of an application’s components. It is one of the most widely used Javascript frameworks in existence today. The USP of Angular JS could perhaps be its unique ability to simplify the development process which is awesome as far as protoyping small apps is concerned. However, the sheer power of the framework enables scaling to full featured client side applications. Despite the developer-enticing advantages such as; Removal of registering callbacks, Non requirement of programmatic manipulation of HTML & DOM, Elimination of boilerplate code etc. a lot of drawbacks in terms of Angular JS usage haunt developers. Let us delve deeper into those so that we know what not to do and why.

Accessing the Scope through DOM

Few optimization tweaks are recommended for production and one of them is disabling debug information. DebugInfoEnabled is a setting which defaults to true and it allows for scope access through DOM nodes. If web developers want to try this, they should select a DOM element and access its scope with: Angular. Element (document.body).scope ( )

Not Using Named Views with UI Router

De-facto routing solution for AngularJS has been the UI-Router and ngRoute is basic for more sophisticated routing. There is a new NgRouter on its way and web development experts term it as basic for more sophisticated routing. UI-Router is prominent because it has awesome basic nesting, route abstraction and optional parameters. Solution to this mistake can be obtained from HTML code and it is necessary to separate them into files and states

Declaring Everything in the Angular World Using Anonymous Functions

This mistake is of very light importance and it is a question of style than avoiding Angular JS error message. If functions are assigned to a variable, web developers can manipulate and mutate functions. The code will be cleaner and it can be very easily split into files. By avoiding this mistake, web development experts get more expressive power through reusable code and splitting all code in self contained blocks is just bette.

JQuerying It-Detached DOM Tree

It is not recommended to use JQuery with Angular JS and it should be avoided at all costs.

Overusing Isolated Scope

There are two reasons for this issue and the first one is that we can’t apply two isolated scope directives to an element and we will have to encounter issues with nesting/inheritance/event processing.

Not Cleaning up Watchers, Intervals, Timeouts and Variables

Not cleaning up any watchers that are not bound to the current scope, intervals, timeouts, variables referencing DOM and JQuery plug-in is a mistake made by even experienced JS Developers. If the above mentioned tasks are not completed manually, we will have to encounter unexpected behavior and memory leaks.

Misunderstanding the Digest

Angular JS updates DOM as a result of callback functions to watchers and watchers are set for many other directives such as ng-if and ng-repeat.

Managing Numerous Watchers

The cycle can cause several performance problems if the number of watchers exceeds about 2000. This is due to the dirty checking that is carried out in a digest cycle.

Common Mistakes Angular JS Developers make

The aforementioned Immediately Invoked Function Expression (IIFE) prints the number of watchers presently on the page. To view the total number of current watchers on a page, just paste the IIFE in the console.

By employing this technique, ascertaining of the existence of duplication or whether unchanging data has a watch is made possible. Use Bindonce to template unchanged data using Angular. Bindonce is a simple directive that allows usage of templates within Angular. However, this does not prevent the count from increasing.

Leaving Batarang On The Shelf

A Google Chrome extension for debugging and developing AngularJS apps, Batarang is a great tool for developers. Batarang enables model browsing to learn the models that are bound to scopes as determined by Angular. This can be useful in isolation of scopes in order to be able to see where the locations are bound. It can also be helpful during working with directives. Whilst entering an untested codebase, Batarang helps determine which services should get the most attention. It also offers a dependency graph.

Offering performance analysis, Batarang enables detection of functions that take the most time in the digest cycle. In addition to the aforementioned benefits, non-utilization of Batarang also prevents developers from viewing the full watch tree, which can come in very handy when dealing with numerous watchers.

Utilization of jQuery

It’s standardized cross platform development and becoming almost a necessity in contemporary web development makes jQuery an amazing library. Albeit despite its appealing and attractive features, the philosophy of jQuery is not compatible with AngularJS. The fundamental difference between the two is that AngularJS is about architecture of applications whereas jQuery is a library for simplifying “HTML document traversal and manipulation, event handling, animation and Ajax.”

AngularJS allows for the extension of one’s HTML vocabulary for the application whereas jQuery compels the developer to think of existing HTML standards. Therefore, in order to truly comprehend the building of an application using AngularJS, the usage of jQuery must be stopped.

AngularJS is a framework that evolves with the community. By refraining from the conventions described above and understanding the reason why, it is hoped that the mistakes made in the usage of AngularJS are not repeated.

EXPLAIN “DEFERREDS”?

Explain “Deferreds”?

Deferreds

  • In their simplest form, deferreds allow you to specify what will occur when a computation/task completes or fails. jQuery’s specific implementation allows you to register callback functions that will run if a deferred resolves successfully, if it is rejected with errors, or if it is notified of some “progress” towards a resolved state (more on that later).
  • The “Deferred” pattern describes an object which acts as a proxy for some unit of computation that may or may not have completed.
  • The pattern can apply to any asynchronous process: AJAX requests, animations or web workers to name a few.

Important to understand:

  • Deferreds can be passed around indefinitely, and callbacks can continue to be added during the entire lifetime of the deferred object.
  • The key to this behavior is callbacks registered with the deferred will run immediately if the deferred is already resolved.
  • You don’t need to worry if the asynchronous unit of computation (e.g. an AJAX request) is finished or not.

HOW REQUIREJS PLAYS A ROLE IN ANGULAR?

How RequireJS Plays a Role in Angular?

It’s the best way of simplifying the task of loading dependencies using AngularJS and RequireJS

One of the basic steps that need to be taken while writing big JavaScript apps is the division of the code base into numerous files. Not only does this help to enhance the maintainability of the code but it increases the possibility of misplacing or missing the script tag on the primary HTML document.

With the increase in the number of files, keeping up a clean record of all the dependencies becomes rather complicated and this issue extends to the case of large AngularJS apps as well. There are few tools that can handle the loading dependencies in the application.

It is important to know the best way of simplifying the task of loading dependencies by using RequireJS with AngularJS along with the way in which Grunt must be used for the purpose of generating combined files holding the RequireJS modules.

Understanding the Basics of RequireJS

RequireJS is a JavaScript library that assists with the loading of JavaScript dependencies at a slow pace. Modules are basically JavaScript files with a few RequireJS syntactic sugar in them and so, RequireJS is capable of implementing the Asynchronous Modules that are specified by the Common JavaScript. You attain the benefit of creating and referring to modules by using the simple APIs offered by RequireJS.

RequireJS should always have a main file that holds the basic configuration data like shims and path modules. The snippet below explains the basic outline of a main.js file:

require.config ( {
map: {
// Maps
},

paths: {
// duplicate names and path of the
modules
},
shim: {
// Modules, plus their dependent modules
}
} );

Every module present within the application does not need to be specified within the paths section and others may be loaded with the help of their relative paths. However, when defining a particular module, the define( ) block needs to be used.

define ( {
// Dependencies
], function (
// object with dependency
){
function yourModule ( ) {
// dependency objects received above
can used
}return yourModule;
});

It is possible for a module to have a few dependent modules but in general, an object will be returned by the end of the module. However, this outcome is not mandatory.

Comparison of RequireJS Dependency Management with Angular’s Dependency Injection:

The difference between RequireJS dependency management and Angular’s dependency management is one of the most frequently asked questions by Angular developers.

While RequireJS tries to load a module, it checks for every dependent module and proceeds to load them first. The objects of the loaded modules are cached and later, they get served when the same page requests once again. However, AngularJS possesses an injector that contains a list of names as well as corresponding objects. Upon creation of a component, an entry is added to the injector and the object gets served whenever it is referenced via the registered name.

Using AngularJS and RequireJS Together:

Most codes for simple applications contain various external dependencies, including:

  1. RequireJS
  2. Angular Resource
  3. jQuery
  4. AngularJS
  5. Angular UI’s ngGrid (Or any component library)
  6. Angular Route

All of the above-mentioned files need to be loaded directly on to the page in a specific order.

How to Define AngularJS Components In Terms of Requirejs Modules?
Almost every AngularJS component is made up of:

  • The Dependency injection
  • A function definition
  • Finally, registering with an Angular module

The first step involves defining a config block which does not depend on other blocks and is capable of returning the config function in the end. However, prior to loading the config module within another module, it is necessary to load every essential component required for the config block. The code below will be contained in config.js:

define ( [ ],function(){
function config($routeProvider) {
$routeProvider.when(‘/home’,{templateUrl:’
templates/home.html’,
controller:’ideasHomeController’})
.when(‘/details/:id’,{templateUrl:’templates/
ideaDetails.html’,
controller:’ideaDetailsController’})
.otherwise({redirectTo:’/home’});
}
config.$inject=[‘$routeProvider’];
return config;
});

The integral point to take note of is the way in which the dependency injection has been carried out in the code snippet above. $inject was used to get the dependencies injected while the config function defined above happens to be a plain JavaScript function. Prior to closing the module, config function must be returned so that it might be sent to the dependent module for use in the future.

The same approach may be followed for defining other kinds of Angular components also, since there is no component specific code contained in the files. The snippet below exhibits the definition of the controller:

define ( [ ], function() {
function ideasHomeController($-
scope, ideaDataSvc) {
$scope.ideaName = ‘Todo List';
$scope.gridOptions = {
data : ‘ideas’,
columnDefs: [
{ field:’name’, displayname:’Name’},
{ field:’technologies’,displaName:’
Technologies’},
{ field:’platform’,displaName:’Platforms’}
{ field:’status’,displaName:’Status’},
{ field:’devesNeeded’,displaName:’
Vacancies’},
{ field:’id’,displaName:’View Details’,
‘cellTemplate:'<a ng-href=”#/details/{{
row.getProperty(col.-
field)}}”>View Details</a>’}
],
enableColumnResize: true
};
ideasDataSvc.allIdeas( ).then(function(
result) {
$scope.ideas=result;
});
}
ideasHomeController.$inject=[‘$
scope’, ‘ideasDataSvc’];
return ideasHomeController;
});

The application’s Angular module is based on each of the modules that have been defined till this point. The file gains objects from all the other files and then hooks them in with an AngularJS module. It is possible that the file may or may not return something as the result of this file, but the Angular module may be referenced from anywhere with the help of angular.module( ). The following blocks of code define an Angular module:

define([‘app/config’,
‘app/ideasDataSvc’,
‘app/ideasHomeController’,
‘app/ideaDetailsController’],

function(config, ideasDataSvc, ideasHomeController,
ideaDetailsController) {
var app = angular.module(‘
ideasApp’, [‘ngRoute’,’ngResource’,
‘ngGrid’]);
app.config(config);
app.factory(‘ideasDataSvc’,ideas-
DataSvc);
app.controller(‘ideasHomeController’,
ideasHomeController);
app.controller(‘ideaDetailsController’,
ideaDetailsController);
});

No Angular application can be bootstrapped using the ng-app directive since the necessary files are loaded in asynchronous manner. The right approach here involves the use of manual bootstrapping and needs to be done in a special file named main.js. This requires the file defining the Angular module to be first loaded and the code is given below:

require {[‘app/ideasModule’],
function( ) {
angular.bootstrap(document,
[‘ideasApp’]);
}
);

Conclusion:

The process of managing dependencies tends to pose a challenge when the application size exceeds beyond a specific number of files. Libraries such as RequireJS make it simpler to define the dependency without having to worry about the loading order of the files. Dependency management involves becoming an essential part of the JavaScript applications. AngularJS 2.0 will receive the benefit of built-in support for AM

WHAT IS THE DIFFERENCE BETWEEN COMPILE AND LINK FUNCTION IN ANGULARJS ?

What is the difference between compile and link function in angularjs ?

In compile phase the angular parser starts parsing the DOM and whenever the parser encounters a directive it creates a function. These functions are termed as template or compiled functions. In this phase we do not have access to the $scope data. In the link phase the data i.e. ($scope) is attached to the template function and executed to get the final HTML output.

Compile – It works on template. It’s like adding a class element in to the DOM (i.e., manipulation of tElement = template element), hence manipulations that apply to all DOM clones of the template associated with the directive.

Link – It works on instances. Usually used for registering DOM listeners (i.e., $watch expressions on the instance scope) as well as instance DOM manipulation. (i.e., manipulation of iElement = individual instance element).

HOW TO ACCESS PARENT SCOPE FROM WITH IN A CUSTOM DIRECTIVE *WITH OWN SCOPE* IN ANGULARJS?

How to access parent scope from within a custom directive *with own scope* in AngularJS?

The way a directive accesses its parent ($parent) scope depends on the type of scope the directive creates:

default (scope: false) – The directive does not create a new scope, so there is no inheritance here. The directive’s scope is the same scope as the parent/container.

scope: true – The directive creates a new child scope that prototypically inherits from the parent scope

scope: { x:’=foo’ } – The directive creates a new isolate/isolated scope. It does not prototypically inherit the parent scope. You can still access the parent scope using $parent, but this is not normally recommended. Instead, you should specify which parent scope properties (and/or function) the directive needs via additional attributes on the same element where the directive is used, using the =, @, and & notation.

transclude: true – The directive creates a new “transcluded” child scope, which prototypically inherits from the parent scope. The $parent property of each scope references the same parent scope.

Solution to Prevent error $digest already in progress when calling $scope.$apply( )?

Solution to Prevent error $digest already in progress when calling $scope.$apply( )?

To check if a $digest is already in progress you have to check $scope.$$phase.$scope.$$phase will return “$digest” or “$apply” if a $digest or $apply is in progress. The difference between these states is that $digest will process the watches of the current scope and it’s children, and $apply will process the watchers of all scopes.

 

What do we do when elements appears as uncomplied/raw elements before page is rendered (like a blink or flicker) in angular Js (Angularjs – ng-cloak/ng-show elements blink)

What do we do when elements appears as uncomplied/raw elements before page is rendered (like a blink or flicker) in angular Js (Angularjs – ng-cloak/ng-show elements blink)?

To prevent the Angular HTML template from being displayed by the browser in uncompiledform while your application is loading, we use the ngCloak directive.

Adding the “display: none” property to the CSS might not be enough to stop the flickering / blink of the elements.If you are loading angular.js in the body the templates aren’t compiled soon, so to prevent the blink we can use the ng-cloak directive and include the following in your CSS:

[ng\:cloak], [ng-cloak], .ng-cloak {

display: none !important;
}

Backend Folks’ take on Angular JS

Backend Folks’ take on Angular JS

Many Backend developers make great use of various application frameworks out there.Given the various kinds of backend frameworks available, web developers have options as to which type of framework they would like to interact from UI standpoint or any frontend framework for that matter. Though there are many frameworks that are very popular some time ago but it becomes more untrendy while the popularity of AngularJS rapidly grows.

As the User Interface is completely moving to the client-side (browser-based), the server-side logic becomes simpler. Moreover, back-end folks (server-side developers) do not have to worry about how to build HTML pages using templates to generate the dynamic content. Rather, they may focus more on optimizing business logic and data persistence using Datastore access and OAuth2 authentication – which then can be exposed as services to client-side.

To better understand the dominance of Angular JS, let’s explore in deep to outline and know why it has become the future wave in developers perspective.

How Java developers are seeing Angular?

AngularJS is mostly popular among companies that builds applications on Java Stack because it makes lots of things easy. After experimenting different javascript frameworks and libraries, most of the Java developers decided to stick with Angular JS. The learning curve of AngularJS is not too steep for Java developers, when it comes to understanding the concepts of containers, dependency injections,and callbacks. They find some similarities in Angular because of their background in Spring/Hibernate. They may have to become more proficient with JavaScript functions, closures and other ‘good’ stuff. But equally important is to be familiar with today’s tooling of a productive Web developer.

Also, JSF and JSP are two technologies that have been widely used to communicate and interact with application up until now. They have been using Java server to exchange the JSON-formatted data with a single-page HTML/JavaScript front end treating the browser only as a rendering platform with no state. Later many moved to other frameworks like AngularJS, as it does most of the stuff Ajax does, and browser technologies were not something that could be avoided, rather used to full capacity to build a ‘client-app’’ than mere ‘web page’.. So many Java Developers started to utilize Angular similar to the power and ease of JSF’s server side data binding, while still being able to unleash the power of client side Javascript.

AngularJS and .NET Developers:

Creating single page apps with Angular and ASP.Net gives developers a great start. Both of them together are compatible to MVC framework with the only difference being, while one is a client side validation (AngularJS) the other favors server side validation (ASP.Net). Senior developers are excited to use AngularJS to make more responsive client side applications with a clear Separation of Concerns (SoC). Many of them are excited to leverage the combination of AngularJS and MVC in order to provide amazing user experiences.

PHP/Python developers view on AngularJS:

Most PHP & Python developers know some level of Angular JS and are in favor of using a Angular MVC framework. Angular MVC frameworks are used for rapid development, many include templating engines which allow PHP developers to create a single page layout which will load different content depending on what page you have visited. Many PHP/Python developers agree that if they are building an application with AngularJS, they must focus on using Angular client-side templates and stay away from server-side templates to avoid incorrect rendering (with Flask/Jinja templates interruption).

Learning curve:

Although AngularJS seemed to be quite new initially, it stood out from the rest with its extensive documentation, its two-way binding, built-in support for unit testing, and clean MVC implementation. Additionally, it lets developers get things done with minimal amount of JavaScript. Many feel AngularJS to be really easy to get started with its new features coming up with and few find it bit difficult when coming from other programming backgrounds. But fortunately, all the tools are quite easy to use along with being lightweight and agile.

Angular attention:

Angular has got huge adoption and fervent support from the community. It gets developers excited on developer productivity, simplicity and clearness in getting things done,without having to spend hours writing a graphical user interface entirely from scratch.