AngularJS for dummies
utopian-io·@beulahlandeu·
0.000 HBDAngularJS for dummies
#### What Will I Learn? - How to use AngularJS #### Requirements - A basic knowledge of Java script #### Difficulty - Intermediate #### Introduction [AngularJS](https://github.com/angular/angular) is an open-source web application framework, with which single page applications (SPAs) are developed. The goal is to enrich web applications with model-view-controller (MVC) capacity in order to facilitate both development and testing. SPAs stand in contrast to round-trip applications that provide static HTML pages from the server. With round-trip applications, ,the browser is reduced to an HTML renderer, while with AngularJS the browser is enriched with extra functionality. AngularJS is managed and maintained by Google and has been available to the general public since 2012. #### Why AngularJS In the Java world, frameworks such as Spring and Hibernate can no longer be ignored. There will be few business ICT projects where no framework is used and only pure Java code is written. In the front-end world (JavaScript) on the other hand, until recently, there were no notable frameworks and there were often used libraries. One can argue that AngularJS is actually the first real mature JavaScript framework. AngularJS can be used within any project where services are accessed through REST. In the development of AngularJS, the philosophy was that building user interfaces should be done declaratively. With AngularJS, HTML can be extended with its own vocabulary. The power of AngularJS lies further in two-way data binding: changes in the model are visible in the view and changes in the view are immediately visible in the model. This makes it possible to test the controller separately. The result is very expressive, readable and fast to develop applications. #### What about JQuery? AngularJS and JQuery use a different approach to application development. JQuery is ideal for manipulating the DOM of the browser to develop a rich web application. AngularJS makes optimal use of the browser in a "strong together" model. AngularJS makes the browser more powerful because semantics can be added. JQuery is a wonderful tool, but large applications often prove harder to maintain and expand. Having said this, AngularJS is based on the core functionality of JQuery. In fact, AngularJS contains a lite version of JQuery. #### Example Hello World Let's show hello world in standard HTML: ```<p>Hello World!</p>``` The result is a straightforward, simple and readable solution. Let's use JQuery to create a hello world application: ``` <p id="greeting"></p> <script> $function (a) { $('greeting').text('Hello World!'); }); </script> ``` The result is a less straightforward and less readable solution. Nevertheless, it is quite easy to see what happens, via DOM manipulation the text Hello World! put. Now let's try it with AngularJS MVC style: ``` <p ng:controller="GreetingCtrl">{{greeting}}</p><br> <script> function GreetingCtrl(a) { this.greeting = 'Hello World!'; } </script> ``` At first glance, this solution seems as verbose as the JQuery solution. There is, however, a substantial difference, the text to be displayed stands, like the HTML example, within the HTML tag. However, in this case, we see a placeholder {{greeting}} which gets the value within the GreetingCtrl controller. For the time being, pure HTML is the winner in all its simplicity. It is, of course, all different if one wants more dynamics: for example that a multi-language Hello World is desired. ##### Example a parrot application We build an application in which the input in a text field is mirrored at a different location on the screen as shown below. ``` This is what I type in This I tap ``` First let's see what the JQuery solution looks like. ``` <input id="veld" value="Jan Janssen"> <p id="groet"></p> <script> $(function (a) { var veld = $('veld'); var groet = $('groet'); function update(x) { groet.text('Hoi ' + veld.val() = '!'); } update(x); veld.bind('keydown', function(a) { setTimeout(update, 0); }); }); </script> ``` This already looks a lot more complex with a lot of procedural code with mostly DOM manipulation. Now we are going to see that AngularJS really excels in these types of applications and the solution that AngularJS offers is as follows: ``` <input id="naam" value='Jan Janssen'> <p>Hello {{naam}}</p> ``` The simplicity and legibility can certainly be called impressive. What we see here is the power of two-way data binding. We can imagine that when the size of an application increases, the complexity increases, making the JQuery solution more and more opaque while AngularJS can keep your grip on your application. ##### Filters and repeaters A very useful standard feature of AngularJS is the repeater directive that allows lists to be displayed easily. Below is an example of the use of such a repeater. ``` ... <ul> <li ng-repeat="product in producten"> {{product.naam}} <p>{{product.beschrijving}}</p> </li> </ul> ... ``` The list of products is the model (as in AngularJS Model View Controller) and we do not need to write complicated Javascript to read this list and then present it on the screen. It is sufficient to declare declaratively, by means of the ng-repeat directive, that we want all products in the list to be shown, with the placeholders determining which fields they are. Now it is often the case that one does not want to show the complete lists (in our example all products) that come from a REST service and one is interested in a subset of this list. AngularJS filters can be used for this purpose. The nice thing about filters is that they can also be determined dynamically. Let's take the previous example and expand it. ``` ... Filter: <input ng-model="myfilter"> <ul> <li ng-repeat="product in producten | filter:myfilter"> {{product.naam}} <p>{{product.beschrijving}}</p> </li> </ul> ... ``` The initial screen will look something like the one below: ``` Filter: - name: Spinach description: Unwashed, origin of the United Sates. - name: Elstar description: Fresh and fruity. - name: Banana description: origin Costa Rica. ``` If a series of characters is entered in the filter field, AngularJS will immediately filter on the product list. In this example, filtering will be applied to all fields because a specific field is not indicated. Example: ``` Filter: her - name: Spinach description: Unwashed, origin of the United States. - name: Banana description: origin Costa Rica. ``` Often, however, one wants to apply the filter to specific fields. Suppose we only want to apply the filter to the description, then we can do the following: ``` ... Filter: <input ng-model="myfilter.beschrijving"> <ul> <li ng-repeat="product in producten | filter:myfilter:strict"> {{product.naam}} <p>{{product.beschrijving}}</p> </li> </ul> ... ``` If we then enter "Banana" the result will be an empty list. ```Filter: Banana``` Test unit Because in AngularJS the controller is disconnected from the view we can start writing real unit tests for our controller. The controller used in the previous product examples is: ``` var productApp = angular.module('productApp', []); productApp.controller('ProductListCtrl', function ($scope) { $scope.producten = [ {'naam': 'Spinazie', 'beschrijving': 'Ongewassen, herkomst Nederland.'}, {'naam': 'Elstar', 'beschrijving': 'Fris en fruitig.'}, {'naam': 'Banaan', 'beschrijving': 'herkomst Costa Rica.'} ]; }); ``` We see that in this controller the model is built up to a list of 3 products. A trivial but typical unit test for this controller can be written as follows: ``` describe('ProductListCtrl', function(x){ it('We verwachten een lijst met 3 producten', function(x) { var scope = {}, ctrl = new ProductListCtrl(scope); expect(scope.producten.length).toBe(3); }); }); ``` As the controller becomes more complex, the unit tests will naturally increase in complexity. ##### Example of an application with backend Javascript applications are ideal for linking with REST backend services and AngularJS applications are no exception. Let's extend the sample application with a link to a REST service with URL http://example.com/greet. This service greets us on the basis of the server room temperature, at more than 25 degrees Celsius the greeting is a warm "Bon dias" and at temperatures less than 25 degrees Celsius the greeting is a cool "Hello". Let us use this in our AngularJS application. ``` <div ng:controller="GreetingCtrl"> <input name="naam"> <button ng:click="groet(x)">Hallo</button> <p>{{groeten}}</p> </div> <script> function GreetingCtrl($xhr) { var selfie = this; this.naam = 'Wereld'; this.groet = function(a) { var url = 'http://example.com/greet'; url += '?callback=JSON_CALLBACK'; url += '&naam=' + this.naam; $xhr('JSON', url, function(code, response) { selfie.groeten = response.groeten; }); } } </script> ``` We see a number of typical AngularJS features pass by. First the directives like ng: controller and ng: click. AngularJS comes with a comprehensive and rich set of directives that supports the most common scenarios in the web application country. Directives unlock the AngularJS core functionality, such as event handling, form validation, and templates. The directive ng: controller links the controller to the web page so that the model (name, greetings) can be manipulated. In this example, the typed name is supplied as a request parameter to the REST service when the button is clicked (ng: click directive). The service, in turn, adds a greeting to the name and returns the result in the response. A second feature is dependency injection (DI). The readers who come from the Java world are probably very familiar with DI, especially when using the Spring framework. In this example we see that the controller uses DI to use XHR; XHR is injected into the controller with GreetingCtrl ($ xhr). This is the way, for AngularJS applications, where one can inject all kinds of services into the controller. It goes too far to describe XHR here, in short, ,it is a way to communicate with the web server. The result, when the button is clicked, is: ```Bon dias World``` Apparently there is a pleasant temperature in the server room. #### Conclusion AngularJS makes life easier for the programmer when building a SPA. The simplicity of AngularJS increases productivity. Moreover, applications become more maintainable because the code becomes leaner and more readable. Further advantages of AngularJS are the testability of the applications and the ease with which applications can be ported to mobile devices. Within a few years, AngularJS has achieved extensive adaptation to the general public. It is almost inconceivable that a new web application project does not bet on AngularJS. #### Sources - [AngularJS](https://angularjs.org/) - https://www.w3schools.com/angular/default.asp - https://en.wikipedia.org/wiki/AngularJS <br /><hr/><em>Posted on <a href="https://utopian.io/utopian-io/@beulahlandeu/angularjs-for-dummies">Utopian.io - Rewarding Open Source Contributors</a></em><hr/>
👍 oadissin, kurtmac, polbot, jewelrana876, cryptoconnector, amicus, evbettor, szokerobert, aymenz, onealfa, embomb701, tradingbroom, rantar, oricaless, alphacore, dexter-k, mykos, zoltarian, harleymechanix, feduzzi, businesswri, steemflow, detlev, bhmcintosh, shadowbot, chanthasam, bigdeej, jonbit, larrydavid4, arunava, orlandumike, youareyourowngod, raja, politi-frantici, intuitivejakob, kiraxoy, tesaganewton, soyrosa,