Blog

AngularJS Tutorial

  • (5.0)
  • | 3045 Ratings
AngularJS Tutorial

In this tutorial, you are going to learn the fundamentals of AngularJS.

What is AngularJS?

Within the rapidly growing JavaScript community, AngularJS burst onto the scene when it released version 1.0 in June 2012. Although a relatively new framework, its powerful features, and elegant tools for structuring applications have made it the front-end framework of choice for many developers. AngularJS was originally developed at Google by testing engineer Misko Hevery, who found that existing tools, like jQuery, made it difficult to structure browser user interfaces (UIs) that needed to display large amounts of sophisticated data. Google now has a dedicated team developing and maintaining AngularJS and related tools. AngularJS also powers some active Google applications, ranging from the DoubleClick Digital Marketing Platform to the YouTube app on the PlayStation 3. AngularJS popularity is growing rapidly:  it powers 143 of the Quantcast Top 10k websites and is rapidly outpacing its closest rivals, KnockoutJS, ReactJS, and EmberJS.

What makes AngularJS so special?

One particularly pithy expression borrowed from the HTTPS://ANGULARJS.ORG/ website describes AngularJS as enabling you to “write less code, go have beer sooner.” The heart of AngularJS is a concept called two-way data binding, which enables you to bind Hypertext Markup Language (HTML) and cascading style sheets (CSS) to the state of a JavaScript variable. Whenever the variable changes, AngularJS updates all HTML and CSS that references that JavaScript variable. For instance, in the following code:

<div ng-show=”shouldShow”>Hello</div>

If the should show variable is changed to false, AngularJS automatically hides the div element for you. There is nothing special about the should show variable: AngularJS doesn’t require you to wrap your variables in special types; the should show variable can be a plain old JavaScript Boolean value.

Although two-way data binding is the basis for what makes AngularJS so useful, it’s only the tip of the iceberg. AngularJS provides an elegant framework for organizing your client-side JavaScript in a way to maximize reusability and testability. In addition, AngularJS has a rich set of testing tools, such as Karma, protractor, and scenario (see Chapter 9), which are optimized for use with AngularJS. AngularJS’s focus on testable structures and rich testing tools makes it a natural choice for mission-critical client-side JavaScript. Not only does it enable you to write sophisticated applications fast, but it also supplies tools and structure that make testing your application easy. As a matter of fact, Google’s DoubleClick team cited AngularJS’s “full testing story” as one of its six biggest reasons for porting its digital marketing platform to AngularJS. Here is a brief overview of some of the concepts that make AngularJS special. All these features would be discussed in AngularJS.

Two-Way Data Binding

In many older client-side JavaScript libraries, like jQuery and Backbone, you are expected to manipulate the DOM (Document Object Model) yourself. In other words, if you want to change the HTML contents of a div element, you need to write imperative JavaScript. For example:

AngularJS inverts this paradigm and makes your HTML the definitive source for how your data is displayed. The primary purpose of two-way data binding is to bind an HTML or CSS property (for instance, the HTML contents or background color of a div element) to the value of a JavaScript variable. When the value of the JavaScript variable changes, the HTML or CSS property is updated to match. The opposite is also true: If the user types in an input field, the value of the bound JavaScript variable is updated to match what the user typed. For instance, the following HTML greets whoever’s name is typed in the input field. You can find this example in this chapter’s sample code as data _ binding.html: Simply right-click on the file and open it in your browser—no web server or other dependencies required!

Subscribe to our youtube channel to get new updates..!

<input type=”text” ng-model=”user” placeholder=”Your Name”>
<h3>Hello, {{user}}!</h3>

The ngModel directive and the {{}}shorthand syntax do all the work.

Scopes in the DOM

DOM scopes are another powerful feature of AngularJS. There is no free lunch with data binding; code complexity has to go somewhere. However, AngularJS allows you to create scopes in the DOM that behave similarly to scopes in JavaScript and other programming languages. This permits you to break your HTML and JavaScript into independent and reusable pieces. For instance,  with two separate scopes: one for greeting in English, the other in Spanish:

<div ng-controller=”HelloController”>
<input type=”text” ng-model=”user” placeholder=”Your Name”>
<h3>Hello, {{user}}!</h3>
</div>
<hr>
<div ng-controller=”HelloController”>
<input type=”text” ng-model=”user” placeholder=”Su Nombre”>
<h3>Hola, {{user}}!</h3>
</div>
<script type=”text/javascript”
src=”angular.js”>
</script>
<script type=”text/javascript”
function HelloController($scope){}
</script>

Testing and Workflow

Providing a framework for writing unit-testable code has been a core AngularJS goal from its first release. AngularJS includes an elegant and sophisticated dependency injector, and all AngularJS components(controllers, directives, services, and filters) are constructed using the dependency injector. This ensures that your code’s dependencies are easy to stub out as necessary for your tests. Furthermore, the AngularJS team has developed numerous powerful testing tools, such as the Karma test runner and the protractor and ngscenario integration testing frameworks. These bring the sophisticated multi-browser testing infrastructure that was previously only feasible for large companies into the hands of the individual developer.

In addition, AngularJS’s architecture and testing tools interface nicely with various open source JavaScript build and workflow tools, such as Gulp and Grunt. With these tools, you can execute your tests seamlessly, tie in tools like code coverage and linting into your test execution, and even scaffold entirely new applications from scratch. Core AngularJS is just a library, but the testing and workflow tools surrounding it make the AngularJS ecosystem as a whole an innovative new paradigm for building browser-based clients. Angularjs training classes include a more detailed discussion of the AngularJS testing ecosystem and the different types of testing strategies you can use for your AngularJS applications.

Angular 6 Training

When Not To Use AngularJS

Like any library, AngularJS is a perfect fit for some applications and a not-so-good fit for others. In the next section, you learn about several use cases in which AngularJS is a perfect fit. In this section, you learn about a few use cases in which AngularJS is not such a good fit and learn about some of AngularJS’s limitations.

Applications Requiring Support for Old Versions of Internet Explorer.

One limitation of AngularJS that may be significant for some users is that it doesn’t support old versions of Internet Explorer. AngularJS 1.0.x supports Internet Explorer 6 and 7, but the version AngularJS 1.2.x supports only Internet Explorer 8 and greater. Furthermore, the current experimental versions of AngularJS, 1.3.x, drop support for Internet Explorer 8 entirely. (They only support Internet Explorer 9 and greater.) If your application needs to support Internet Explorer 7, using AngularJS is probably not the right choice.

Applications That Don’t Require JavaScript Server I/O

AngularJS is an extremely rich and powerful library, and avid users are often tempted to use it for every application. However, there are many cases in which AngularJS is overkill and adds unnecessary complexity. For instance, if you need to add a button to a page that shows or hides a div element whenever a user clicks on it, using AngularJS cannot help you unless you need to persist the state of the div in the page’s URL or to the server. Similarly, choosing to write your blog in AngularJS is usually a poor decision. Blogs typically display simple data with limited interactivity, so AngularJS is often unnecessary. Also, blogs require good integration with search engines. If you were to write a blog in AngularJS, you would need to do some extra work to make sure search engines could effectively crawl your blog, because search engine crawlers don’t execute JavaScript.

When To Use AngularJS

Now that you’ve learned about a couple of AngularJS’s limitations, you’ll learn about a few use cases in which AngularJS truly shines.

Internal Data-Intensive Applications

AngularJS is an extremely powerful tool for applications that need to display complex data in a browser UI, such as continuous integration frameworks or product dashboards. Much of the challenge in developing UIs for these applications lies in writing imperative JavaScript to render data correctly every time it changes. Two-way data binding frees you from needing to write this glue code, which results in much slimmer and easier-to-read JavaScript.

Mobile Websites

AngularJS has extensive support for most common mobile browsers (Android, Chrome Mobile, iOS Safari). Furthermore, AngularJS has powerful animation support, and single-page apps enable you to leverage browser caching to minimize your bandwidth usage. This enables you to build mobile web applications that are fast and effectively mimic native applications. In addition, frameworks like Ionic enable you to build hybrid mobile applications, applications are written in JavaScript but distributed through the Android and iPhone app stores, using AngularJS.

Building a Prototype

One theme that appears numerous times in this Angularjs training is the idea of two-way data binding creating an effective separation between front-end JavaScript engineering and user interface/user experience (UI/UX) design. Two-way data binding enables the front-end JavaScript engineer to expose an application programming interface (API) that a UI/UX designer can then access in HTML, enabling both the front-end engineer and the designer to work in their preferred environments without stepping on each other’s toes. This is particularly useful for building out a prototype browser UI quickly because you can then effectively parallelize tasks and enable your team to run more smoothly. In addition, AngularJS’s rich testing ecosystem enables you to ensure solid test coverage, and thus make sure your prototype doesn’t have any obvious bugs when you present it.

Frequently asked AngularJS Interview Questions

AngularJS VS ReactJS

It is quite true that for any business in the present time, it is necessary to have the right framework for a novel JavaScript system. There are certain things to pay attention too and business often fails to keep up the pace because of issues like complex codes, code maintenance as well as overall durability of the project. Selecting the most appropriate technology is therefore vital. You might have no idea that AngularJS and React JS has gained a lot of popularity in enabling businesses meeting such needs. This doesn’t actually mean both can be put equal in every aspect. Actually, there are certain things that make them different from each other. In this post, both the technologies are compared to let you know which one is best and why.

When it comes to performance, both can be considered with closed eyes. There are several advanced features both React and Angular are equipped with which in fact makes them preferable all over the world. As per a recent survey, ReactJS has more users than AngularJS. However, the latest update of AngularJS i.e. Angular 2 has been ranked as the number two most famous framework across the globe after ASP.NET.

The biggest and in fact the true factor that contributes in this matter is nothing but the global support community of AngularJS. A lot of developers are out there which call it one of the finest frameworks in every aspect. Actually, many designers are working with developers and are also contributing to enhancing the overall reliability, as well as the credibility of AngularJS. It is equipped with a unique feature and i.e. two-way data binding which makes it simple to work with. Also, AngularJS is considered as a full-fledged framework. It contains many top class features when compared to ReactJS. In addition to this, it simply prompts rendering.

Factors that make ReactJS better:

On the other side, ReactJS is simple and faster than AngularJS. Also, it is simple quick and reliable to work with. The complexity of AngularJS is one of the leading factors that make several programmers and developers across the globe simply say no to it. A lot of emphases is required to make the apps safe as well as reliable and this is another problem with AngularJS. In addition to this, there is another factor that makes ReactJS a wise choice and i.e. its ability to enable developers to understands the ways codes can be reduced.

In addition to these, there are other two major factors that contribute a lot to making ReactJS simply the best. The first one is its SEO-friendly approach. Yes, it’s true that ReactJS always ensure outcomes that are friendly with search engines. Thus you can always make sure of having top web rankings of your website without doing much. Another feature it has is nothing but its efficiency. It is widely regarded as one of the highly efficient frameworks. Facebook has given a lot of emphasis on making it stand alone against other frameworks. Moreover, a lot of costs can be saved if you know how to consider ReactJS properly.

Skills required in both these approaches:

One of the very well-known facts about the ReactJS is it’s not a full-fledged framework just like AngularJS. Therefore integrating MVC framework with UI library of ReactJS needs a lot of programming skills. Also, it’s a time-consuming process. This doesn’t actually mean that handling AngularJS is an easy job. Basically using both these technologies has become a major challenge for those who don’t have a lot of experience in programming. The one simple reason is both of them lack a comprehensive guide. Also, there are a few protocols associated with both which is actually very complex and need a lot of expertise for their clear understanding.

Both AngularJS and ReactJS are capable to provide approaches that are different. Actually, both these technologies have contributed to making web development superior since the past few years. If you are a small-scale business owner, you can proceed with any of these options. In a real sense, none of them is superior to others. It is also possible to integrate them with other frameworks in case the need of same is felt.

Technology is blooming at a very fast speed. In the present scenario, developers are able to take the full benefits of the same when it comes to developing most scalable web page applications. Actually, frameworks such as AngularJS and Angular 2 have played a very significant role in this matter. You might have no idea but AngularJS is a popular framework maintained by Google and angular 2 is nothing but the advanced AngulaJS version. However, there are a few things that put them separate from each other.

AngularJS vs. Angular 2

Although both are almost equally powerful, using them can be different depending on the type of results. In this post, we will put some spotlight to let you understand how AngularJS and Angular 2 are different from each other.

[Related Page]: Angular Versions

Architecture Limitations

Angular 2 has a better architectural framework. Actually, there were some of the key issues related to the same in the AngualrJS. Google has improved a lot in Angular 2. The current version available has some of the visible changes which are actually not compatible with AngularJS. Google claimed that Angular 2 has eightfold speed boot for both updating pages, as well as rendering. A tool is presently available through which both the framework can be merged with each other and it's possible to use Angular 2 on web pages developed through AngularJS

Angular S has some of the excellent features than AngularJS. The API’s has been made extremely simpler. When it comes to debugging, programmers have no reason to worry about anything. The powerful template is another best thing about Angular 2.

Improvements Related To Performance

One of the key problems in AngularJS is bootstrap was not platformed specific which often degrade the performance. However, the same has been made specific to platform in the new version i.e. Angular 2. As far as the matter of mobile support is concerned, JS works well when it comes to two-way binding and responsive designs but lacks mobile support. For running on mobiles, it largely depends on libraries. On the other side, Angular 2 has mobile friendly architecture. Libraries such as Native Script are capable to boost mobile development.  This is one of the leading features in angular 2 when compared with Angular JS.

Rendering The Similar Code in  Different Manner

Angular 2 is widely appreciated by a huge community of programmers all over the world. The reason is it enables them to render similar codes in different manners without facing any issue. In addition to this, coding can actually be done quickly when compared to Angular JS.

Angular 2 AngularJS
It is faster than AngularJS in every aspect As compared to Angular 2, Angular JS is not fast.
Has extended mobile support It lacks mobile support
The syntax is similar to JAVA The syntax doesn’t match the same in AngularJS
It is totally component-based programming It uses component-based programming up to a limit.
Classes are well-defined in Angular 2 Classes are not well-defined when compared to AngularJS.

Key Difference

Developers are considering Angular 2 in the present time mainly because it doesn’t depend on $ scope. In AngularJS, it is considered to glue controller and view. Actually, Angular 2 has enabled programmers to save their valuable time by writing fewer codes and attaining maximum scalability for similar projects. Angular 2 always make sure of faster entities

Checkout Angular 8 Tutorial

Dependency Injection

There are numerous opportunities for object-based work, as well as for components in Angular 2. This is due to the enhanced dependency injection. There is a total of three parts in the injection in case of Angular 2. There are injectors which consist of APIs. The same is used to inject the dependencies. The best thing in the case of Angular 2 when compared with AngularJS is the object only needs to be passed through injector view, while in case of AngularJS, developers first have to pass through the same from constructor’s components. Maybe every developer should be updated through AngularJS Training to keep them updated in the tech field.

This is how both AngularJS and Angular 2 are different from one another. You can now choose the one that you finds suitable for you. Angular 2 must be considered for developing the latest web page applications. However, AngularJS has better support as there are lots of programmers who are familiar with it. Angular 2 on the other side is new technology but it has features better than AngularJS.

AngularJS vs. JQuery

JavaScript tools are gaining a lot of attention at the present time. This is mainly because of their ability to make things in application development simple and reliable. You might have no idea that AngularJS and JQuery are the two very popular JavaScript tools of the 21st century.

JQuery is basically a Document Object Model library which is helpful in cutting down the complexity from the processes of using JavaScript on a website. Actually, JavaScript plays an excellent role in making WebPages look attractive and dynamic. JQuery is capable to consider the difficult code that is needed to make AJAX calls. It converts the same into simple strategies that can be considered through a single line of JavaScript.

How AngularJS and JQuery are different

In JQuery you can find options for DOM manipulation whereas the same is not present in AngularJS. Event handling is not at all a big deal on JQuery while the same task is very complex on AngularJS.  Also, JQuery assures cross-browser compatibility whereas in case of AngularJS the same task is very difficult. JQuery is simple to use and light whereas the latter needs expertise in handling it properly.

Both these technologies can be considered for any type of webpage applications development. However, you need to pay close attention to the pros and cons associated with both. JQuery can be used in conjunction with other frameworks while you cannot do the same in case of AngularJS.

Developer’s opinion

Because JQuery is structureless, developers can proceed with tasks in the way they see them. It must be noted that lack of structure can sometimes result in a very complex code. It is because of no other reason than this JQuery is considered as a confusing approach at several stages during the development. On the other hand, AngularJS can simply be considered without worrying about anything like this.

With AngularJS a structured environment can simply be provided for SPA. Thus the chances of having a complex code can simply be reduced. AngularJS is actually equipped with features that let the developers impose a strict upper limit on the length of code without compromising with anything. When it is compared with JQuery, it doesn’t encourage the use of any library up to a large extent. Developers appreciated AngularJS because they can simply use HTML as a template language.

There are more features in AngularJS than JQuery and this is another factor that adds more to its popularity. It enables developers to simply work with MVC, form validation, templating beyond the limit and use angular directives.

What you must choose

In case you need to manipulate the DOM with JavaScript, obviously, JQuery is a better option to consider. It is best for light and powerful outcomes. Also, if you need to have some unique features on your website, this is exactly what that you should consider. There are almost no chances of data binding with this approach. Also, you can simply integrate the technology into an angular directive through customization. In case of flexibility is one of your prime needs, you must go with AngularJS.

AngularJS is excellent for two-way data binding. It enables you to keep a close eye on the needs of your present as well as future clients. Engaging, as well as stunning applications can simply and quickly be created with the help of this approach. Also, AngularJS is capable to eliminate the code repetition which always ensures scalable outcomes. Because it’s an Open source approach, there is no need for you to worry about customization. In fact, it all you need is customized outcomes, AngularJS is a better approach.

Support availability

There are a very large number of experts all over the world for both these technologies and thus you need not worry about anything. Even if you stuck anywhere while developing the complex applications and WebPages, you can simply keep up the pace through various forums and online support websites.  The best thing about both of them is they are compatible with almost all the browsers and Operating Systems.

AngularJS is known to have inbuilt support for AJAX queries. You cannot expect the same from JQuery. Client-side applications can easily be written in a reliable manner through AngularJS.
Now you are familiar with the pros and cons associated with both these approaches. You can choose them as per your needs. However, it must be noted that both these technologies can be trusted in the long run. AngularJS promises better results and more scalable applications than JQuery while developing large scale apps.

What are AngularJS Directives?

AngularJS provides us with a provision to extend the original HTML elements with newer attributes, and the amalgam of the original element with added features are coined as DIRECTIVES. On the whole, AngularJS Directives can be thought of markers on a DOM element (just like an attribute, element name or CSS) which tell the AngularJS’s compiler ($compile) that the element comes along with additional behaviors (example, by event listeners or the like). 

How to use built-in AngularJS Directives?

Now that you know what directives are (well, superficially), AngularJS provides a set of directives by default and also provides a provision to create your own new ones. The built-in AngularJS directives are the ones with the prefix ng- and there are quite a few that we would want to introduce right away.

A thorough list of all the available AngularJS built-in directives can be found here.

  • ng-app AngularJS directive is used to initialize an AngularJS application
  • ng-init AngularJS directive is used to initialize application data with values
  • ng-model AngularJS directive is used to bind the value of HTML controls with any of the application data that we might, using the ng-init directive as explained above.

Let’s look at an example to understand, where and how these directives could be used. If you’re not able to understand everything on the first go, don’t panic – there’s clear explanation below on how each of the element works (also helps you with the technical know-how about these directives).

Input something (if you wish):
TV Series:
Episode  :
You're referrring to wrote: Game of Thrones Season 4 -> Spoils of War

If you run the above code, you should be able to see the following displayed on your browser:

Now let’s try to understand what each of the directives used means to achieve the final output that we are seeing. To start with, the ng-app directive tells AngularJS that the holding it owns your AngularJS application. In other words, it defines the root element of your AngularJS application, and also it will automatically initialize the application when you load your page. The ng-init directive tells what each of the parameters namely ‘seriesName’ & ‘episodeNumber’ would hold by default for your AngularJS application. Using ng-init is not very suggestible and in the coming sections, you’ll understand how to initialize data using controllers. Now trying to understand the ng-model directive, it tells that the element matches the tags. ng-model can also be used for providing type validation checks for data types, provide CSS classes for HTML elements and also to bind HTML elements with the HTML forms correspondingly.

In the example above, we have also shown the concept of ‘Data Binding’ – which in AngularJS is to bind AngularJS expressions to AngularJS data from the application. Game of Thrones is therefore bound with ng-model=”seriesName”.

How to create new AngularJS directives?

AngularJS directives can be broadly classified into four flavors, namely:

  • A new HTML element
  • An attribute on an element
  • As a class
  • As a comment

This background should be good enough for us to get onto the quest of writing our own custom AngularJS directive. A directive can be treated the same way as a controller for its registration. The difference would be that while registering a directive you get a directive definition which has a lot of properties to configure the directive. Let’s get down to some action in creating a custom directive then:

var justAnotherVariable = angular.module(‘myAngularApplication’, []);
    app.directive(‘customDirective’, function(){
        return {
            restrict: ‘AE’,
            replace: ‘true’,
            template: ‘Hello AngularJS Aspirants, this is my custom directive!!!’
        }
});

Using app.directive() we have registered a new custom directive named myCustomDirective. The function, which is the second parameter to the command above is the directive definition that we were discussing earlier. Let us be HTML5 compliant to access our new directive in this format (shown below):

OR

That should be it, the directive created above does nothing much than display some static text. But there are some interesting facts that can be understood about the properties that are used in the directive definition object to configure it.

  1. restrict: This property conveys how the directive can be used in an HTML as. Since that we’ve set it up as AE, this directive can be used as a new HTML element/attribute.
  2. template: This property is nothing but the HTML markup that will be compiled and linked by AngularJS. Here for an example, we have limited it to a simple string but in actual this can be much more complex including other directives or expressions.
  3. replace: This property specifies that the generated template will replace the HTML element upon which our custom directive is invoked. Since that we’ve set it to true, the final output would be Hello AngularJS Aspirants, this is my custom directive!!!

Tips & Tricks to debug your directives:

This section talks about simple tips and tricks that can be applied to help you debug your directives code more efficiently. The very need of it is because of the compiled version of the directives won’t be sufficient to analyze issues. If you want to see the actual directive that was used – when you want to rely on the uncompiled version of the directive. In such a case, you might want to use ng-non-bindable. To explain this a little better, let us take an example of a widget that prints the current season’s episode names of the famous TV series (Game of Thrones). 

The episodes' scope variable will be coming from the controller, and it would give the following as the output:

Dragonstone
Stormborn
The Queen’s Justice
Spoils of war

Now, if you wanted to check the actual directive usage, then this code should be helpful. It will enable you to see the uncompiled version of the code, thus enabling you to debug your directive efficiently.

•
•{{episodes}}
•

Now with the change above, the output is definitely going to be different than the earlier:

{{episodes}}

How to Unit-test your AngularJS directives?

Now that you’ve covered the major chunk of the AngularJS directives development, now is the time for you to concentrate on how you test these to prevent any possible bugs. This section will not give you deep insight into the Unit test framework as such, but will definitely be good enough to get things started. Let’s use Jasmine for unit testing and Karma for the unit test runner. Karma can simply be installed on your system by running the following command - npm install -g karma karma-cli (This works under the expectation that you have both Node.js and npm installed on your system). Once the installation is completed, get on to a command line and run karma init.

You can answer the questions that pop up, like which testing framework to use (jasmine), want to capture any browsers automatically (Chrome) and etc to finish the installation process. Executing all the tests that are configured in your karma conf is as simple as right clicking on karma.conf.js and then click on Run karma.conf.js. You can also run tests with the karma start command line in the project root folder. That is all which is required for you to set up and execute all your tests using karma. 

AngularJS is the best available UI framework to develop modular and testable web projects within no time. There are many other flavors of such UI frameworks, but none that matches the might of AngularJS. It becomes very important to gain deeper knowledge into all of the available directives to build a pleasing application and to also know what is available for ready usage and what needs to be developed based on your project requirements. The more you practice, the more you will be able to appreciate the inner workings of these directives. I hope that this article has helped you understand both the built-in and new AngularJS directives well.

AngularJS Filters

Filters are used to format or to modify the data of an element or used along with an expression or directive (with a pipe character).

AngularJS provides quite a good number of built-in filters, and as you’ve seen earlier, building a new filter isn’t that tough either.

AngularJS filters What are they??

Here is the list of built-in AngularJS filters that one can use without even a second thought. Filters are executed when their inputs have altered in conjunction with templates. Filters can be used in conjunction with controllers, services and directives.

Without further delay, let’s get deep diving into the concepts and the usage of filters.

Classification of built-in AngularJS filters:

  • String filters
‘Hello {0}, How is {1} doing?’ | string.format : ‘Samwell Tarley’ : ‘Ser Jorah Mormont’

will result in this string Hello Samwell Tarley, How is Ser Jorah Mormont doing?

lowercase: This filter is used to convert all the uppercase letters of a string to lowercase

‘CErSEi LANNISTer’ | string.lowercase 

results in Cersei Lannister

  • Array filters

join: This filter is used to join a given series of data types to a resultant single string.

[‘CERSEI’, ‘JAIME’, ‘TYRION’] | array.join:’, ’ results in CERSEI, JAIME, TYRION

reverse: This filter reverses the order of elements present in the given array.

ng-repeat=’[“CERSEI”, “JAIME”, “TYRION”] | array.reverse’ results in “TYRION”,“JAIME”,”CERSEI”
  • Math filters

max: This filter is used to find out the maximum value of the available list of numbers.
[5, 9, 4, 1] | math.max results in 9

min: This filter is used to find out the minimum value of the available list of numbers.

  • Boolean filters

YesNo: This filter is used to evaluate the Boolean expressions as a YES or a NO accordingly.

‘CERSEI’==’SANSA’ | binary.YesNo results in No

5. Debug filters

print: This filter is used to print the value bound to an element.

‘DebuggableValue’ | debug.print prints DebuggableValue

The filter Filter:

The filter Filter selects items from an array based on the criteria specified and then returns a new array as an output. The criteria for the filter Filter can be a String, Object, or a function altogether. We can optionally do a stricter comparison of the criteria from the available list of values based on the value provided.

The following example will you give you a clear idea of how this works:

AngularJS filter Filter Demo:

Name to search:

Result: 

 {{mySearchArrayElements | filter:nameSearchCriteria}}

results to the following screen for us to input a certain name, as follows: and when a search criterion is entered, check how the Result attribute gets changed:

How to build our own custom AngularJS filter?

Writing a custom filter of our own is just a cake walk, but for the better good of the new AngularJS aspirants, we will take it really slow. The step is just to make sure that you register a new filter factory function with your module. The basic expectation out of a custom filter function is that it should be a pure function, meaning, it should always return the exact same result given the exact same input value. AngularJS makes it very stringent on following this contract and makes it a point to execute a filter function code only when the inputs to the function are changed explicitly.

Our custom filter is going to identify the name of the day by taking a number as input (for example, 1 is Monday and so on). So let’s get down to business in writing our own filter.

app.filter(‘identifyDayByANumber’, function(){
    return function(number) {
    if(number === 1) {
        return ‘Monday’
    } else if(number === 2) {
        return ‘Tuesday’
    } else if(number === 3) {
        return ‘Wednesday’
    } else if(number === 4) {
        return ‘Thursday’
    } else if(number === 5) {
        return ‘Friday’
    } else if(number === 6) {
        return ‘Saturday’
    } else if(number === 7) {
        return ‘Sunday’
    }
}
})

The filter code is just checking the number that is being passed to it and based on the number that is being passed to it, evaluates which day of the week it is. Simple isn’t it? Now let’s see how we can use this filter in practical use, shall we?

Applying the filter that we have created above as follows, results in the day just as expected. Please check this out:

{{ 6 | identifyDayByANumber }} 

results on Saturday

Now let’s negative test our filter that we’ve created above by passing ‘Saturday’ as input and see what happens:

{{ ‘Saturday’ | identifyDayByANumber }}

results in Saturday again as the input doesn’t evaluate to a value in any of the filter conditions, hence comes the way just as it was sent to it.

Now what we can learn from the negative test that we have done above, it is a good practice to provide the proper datatype to your filter based on your requirement and if none of the conditions are met then you should remember to send the input as is without any modifications.

How to Unit test your filters?

Each built-in filter is covered by Unit tests and any of the filters that you create can also have unit tests as well. Running unit tests as explained earlier is very simple, run just the following commands.

npm run karma
npm run karma2

Let us write some unit tests for our filter, so that we can also see how the execution of these would work against our filter code.

describe(‘identifyDayByANumber’, function() {
    beforeEach(module(‘core’));
    it(‘should convert given number to a weekday’, inject(function(identifyDayByANumberFilter)) {
        expect(identifyDayByANumberFilter(1)).toBe(‘Monday’);
        expect(identifyDayByANumberFilter(7)).toBe(‘Sunday’);
})
);
});

As you’ve observed, while injecting a filter there is a definite need for us to suffix the filter name with ‘Filter’. For instance, our identifyDayByANumber filter is injected as identifyDayByANumberFilter.

Today we have learned about AngularJS built-in filters, had a custom filter built in the form of identifying the day by a number. Building filters is the easiest job while using AngularJS but then a point to remember is that you need to keep your code clean. A point not to forget is that the sole purpose of a filter is to modify/change/alter the element value and when we are unable to do that, we need to ensure that we send back the input value untouched.

Difference AngularJS vs Factory

Intro to AngularJS service vs. factory

Since last few years, internet users have increased rapidly. A lot of people in the present scenario perform a lot of tasks through the World Wide Web. This is exactly what that makes businesses adopt simply the best framework and technologies to come out with most scalable web applications. The reason behind this is very simple and i.e. adding more clients through the internet and help existing ones to get all the information they need or to access the services online. Obviously, this needs proper implementation of everything. If you are using AngularJS approach, there are certain things you need to consider and Angular Service and Factory is among them. Check out the difference between the two in the below paragraphs.

There are certain things which make Angular Service different from the factory. Angular plans to make HTML WebPages more dynamic and in this way more valuable to the programmers, while likewise giving a solid structure through which components can be made rapid and effective in all the aspects. The front-end developers are presently looking for approaches to consider interfaces immediately when the JavaScript coding can generally be exceptionally tedious and complex as well.

What is Angular service?

An angular service is a well-known approach that is useful for us when it comes to keeping the data across the app permanently. Data can easily be transferred, controlled or communicated across the controllers in a very reliable and meaningful way through Angular Service. In addition to this, developers always have the freedom to consider it for sharing, as well as organizing the functions and data across the application. One thing you need to keep in mind in that it’s basically a singleton object and in actual sense, it gets represented only once per application. However, when this is compared with an Angular function, developers can represent it again and again in an application. Developers often call it a lazy approach as it consumes a lot of time.

Similarity between Angular Service and Factory

As compared to functions, Service is a bit confusing. Basically, it is very easy to register the objects as factories and services in Angular. Both of them bear a similar behavior and this is exactly the reason most of the users proceed don’t look into detail while considering them. Actually, Services are different from factories in many ways. If both are compared, there are certain things that become clear. The very first thing is both service and factory are singletons. There are a lot of developers and programmers who are using them both for modeling the behavior of an object. Although both contain state variables which are internal, writing the code in both the cases is extremely different.
Understanding the factory

Basically, Angular factory is a function which provides a value which gets injected into the objects. The code can be made more recognizable very easily. Factory is basically very simple to work with when compared to Service. There are certain things that add a lot to its overall features and make it simply the best. 

Service is basically a very simple approach in which take a function and a name that clearly defines the service after which it is possible for developers to inject and use the same service into directives, controllers, filters and several other components. One thing which is clear from this is factory is not a constructor function whereas service is. 

Which one to consider?

There is nothing wrong to say that a lot of developers consider factory over Service. The reason is very simple and i.e. it is possible to run the code prior to returning the object literally.  Many users believe the same is not possible in case of service. Return object literals is also possible in case of Services. Therefore it is possible to take the service code and consider it in a similar manner as in case of function.

This is how both these approaches are different from one another. There are certain facts listed in the post here which you can consider to know the exact difference. It must be noted that both seem very similar in a number of things but in a real sense, several factors make them different from each other. Angular Service and function both are powerful in performing their task if you know how to use them wisely.

Explore AngularJS Sample Resumes! Download & Edit, Get Noticed by Top Employers! Download Now!

Subscribe For Free Demo

Free Demo for Corporate & Online Trainings.

Ravindra Savaram
About The Author

Ravindra Savaram is a Content Lead at Mindmajix.com. His passion lies in writing articles on the most popular IT platforms including Machine learning, DevOps, Data Science, Artificial Intelligence, RPA, Deep Learning, and so on. You can stay up to date on all these technologies by following him on LinkedIn and Twitter.


DMCA.com Protection Status

Close
Close