Tag Archives: AngularJS

TOP MISTAKES DEVELOPERS DO WHILE CODING WITH ANGULAR

Top Mistakes Developers Do While Coding with Angular

Top Mistakes Developers Do While Coding with Angular

AngularJS is one of the most popular JavaScript frameworks accessible today. AngularJS major goal is to bridge the development process which makes it great for prototyping small applications, but its power allows scaling to full-featured client-side applications. The combination affluence of development, breadth of features, and performance has led to wide implementation, and wide implementation comes with many common drawbacks. This list captures common AngularJS mistakes, so explore this article and know the major mistakes done by developers while coding with Angular.

USING NGONCHANGES TO SPOT QUERY LIST CHANGES

In Angular 1, if the user wanted to be notified when a value changed, the user has to set a $scope.$watch and physically check for changes in each digest cycle. In Angular 2, the ngOnChanges links greatly and streamlines this process. Once the user defines a ngOnChanges method in his/her component class, it will be called whenever the component’s inputs change.

But, the ngOnChanges method executes only when the component’s inputs change -especially, those items the user have included in his/her inputs array or explicitly labeled with an @Input decorator. It will not be called when items are added or removed from @ViewChildren or @ContentChildren query lists.

If the user wants to be alerted for changes in a query list, then the user should not use ngOnChanges. In its place, the user should subscribe to the query list’s built-in observable, it “changes” property. As long as the user do so in the proper lifecycle link, the user will be alerted whenever an item is added or removed.

@Component({ selector: ‘my-list’ })
export class MyList implements AfterContentInit {
@ContentChildren(ListItem) items: QueryList;

ngAfterContentInit() {
this.items.changes.subscribe(() => {
// will be called every time an item is added/removed
});
}
}
CALLING DOM APIS DIRECTLY

There are very few circumstances where manipulating the DOM directly is necessary. Angular 2 provides a set of leading, high-level APIs such as queries that one can use instead. Leveraging these APIs confers distinct advantages:

  • It is possible to unit test the application without touching the DOM, which removes difficulty from testing and helps the user tests run faster.
  • It decouples the user’s code from the browser, allowing the user to run the application in any rendering context, such as web workers or outside of the browser completely.

When the user manipulates the DOM manually, the user will miss out the above advantages and ultimately end up writing less expressive code.

QUERY RESULTS IN THE CONSTRUCTOR

While playing around with queries, it is easy to fall into this ploy.
@Component({…})
export class MyComp {
@ViewChild(SomeDir) someDir: SomeDir;
constructor() {
console.log(this.someDir);    // undefined
}
}

When the console logs are “undefined”, the developer might assume the query is not working or the developer itself constructed it imperfectly. It is important to remember that query results are not yet available when the constructor executes.

BINDING TO THE NATIVE “HIDDEN” PROPERTY

In Angular 1, if the user wants to adjust the visibility of an element, the user can use one of the Angular’s built-in directives, such as ng-show or ng-hide

Angular 1 example:

<div ng-show=”showGreeting”>

Hello, there!

</div>

In Angular 2, template syntax makes it available to bind to any native property of an element. This is very powerful and opens up a number of possibilities. One option to bind to the native hidden property, which is similar to ng-show, and sets the display to “none”.

Angular 2 [hidden] example:

<div [hidden]=”!showGreeting”>

Hello, there!

</div>

At first sight, binding to the hidden property seems like the closest cousin to Angular 1 ng-show. However, there is one “!important” difference.

ng-show & ng-hide together handles visibility by adjusting “ng-hide” CSS class on the element, which sets the show property to “none” when applied. Importantly, Angular controls this style and postscripts it with “!important” to assure that it always overrides any other display styles set on that element.

THE VERDICT

AngularJS is a great framework that continues to grow with the community. AngularJS is still a growing concept, but hopefully by following these pacts some of the major pitfalls of scaling an AngularJS can be averted.

PROVIDE A QUICK SUMMARY OF DIFFERENCES BETWEEN ANGULARJS SERVICE, PROVIDER AND FACTORY?

Provide a quick summary of differences between AngularJS Service, Provider and Factory?

Quick summary,
Service: create a new instance upon every injection. Utilize ‘this’ object inside the service
Syntax: module.service( ‘serviceName’, function );

Factory: return the value saved in factory object upon every injection. Need to create an object, add methods & properties to it and return that object.
Syntax: module.factory( ‘factoryName’, function );

Providers: Can be configured during the module configuration phase
yntax: module.provider( ‘providerName’, function );

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.

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