How do I use the Angular ngIf Directive?

Angular

Angular logo - ngFor

Angular’s ngIf directive does not simply hide and show. It creates and destroys an HTML element based on the result of a JavaScript expression.

It’s perfectly fine to use the Angular ngIf directive to hide / show one or more HTML elements. This is the net effect and when used wisely, there is no problem with this usage. But it is important to be aware that Angular’s ngIf directive actually creates a DOM element or destroys it. If you want to actually hide / show elements without destroying them, then the Angular ngClass attribute would be more appropriate.

The thing to keep in mind when considering whether or not to use the Angular ngIf directive is performance. For example, if you have have hundreds of DOM elements, but do not need to show ALL of them when the component initially renders, then the Angular ngIf directive might be better for performance reasons. As you’ll see, the benefit of this is that only tens or a few hundred DOM elements are created at a time. So this means that as your data changes, the creating / destroying of elements is restricted to fewer elements. But if you have a total of tens or perhaps less than 100 DOM elements to manage in your component, then the Anglular ngClass attribute might be a better choice. You’ll find that performance is improved when using the Anglular ngClass attribute because DOM elements will be hidden-shown via CSS, not JavaScript

Example # 1

In Example # 1, we have our component. There is a contentVisible property. It is a boolean, and set to false by default. We will consume the contentVisible property in our template (see Example # 2).

Example # 2

In Example # 2, we have our template. Notice that the div element has an ngIf attribute. This attribute’s value is the result of the contentVisible property. So if the contentVisible property is true, then the div element is created. Conversely, if the contentVisible property is false, then the div element is destroyed. The net effect is that the element is hidden / shown, but it is important to note that the element is actually created / destroyed.

There are two buttons in the template. Each button has a click event handler. In each case, the button sets the value of the contentVisible property. Each button also has an ngIf attribute. Because they both change the value of the contentVisible property, they change the visibility of both buttons. That is to say, when the first button is clicked, it is immediately destroyed and the other button is created, and vice verse.

The main thing to note in this example is that these buttons change the value of the contentVisible property, which seems to hide / show the div. However, the div is actually being created and destroyed.

Video Example Code

If you want to download the example code, visit this Github page, and then follow the instructions: bit.ly/kcv-ngIf

Summary

So, it’s important to understand that the Angular ngIf directive actually creates and destroys DOM elements. The Angular ngIf directive could be a strong or weak design choice, depending on the context of your component. It’s also a DOM management choice, and whether or not you’re working with hundreds or thousands of DOM elements. So, overall, the approach you take could have a major impact on the performance of your component.

Getting Started with Angular 1.x Custom Directives – Part III – The “restrict” property

Angular

Angular.js LogoLearn how the “restrict” property determines how your Angular.js directive can be invoked

In the second part of this series: Getting Started with Angular.js Custom Directives – Part II – The “replace” property, we learned about how to use the “replace” property when creating a custom Angular.js directive. This determines whether the element that your directive renders will be a child of the element that invoked it, or a complete replacement of that element.

In this article, we will learn about the “restrict” property that, which allows you to specify the ways in which your custom directive can be invoked.

Example # 1:

 

In Example # 1, we have created a custom Angular.js directive named: “uiWidget”. In addition to the “template” and “replace” properties that were discussed in previous articles, we have created a “restrict” property. This property allows you to specify the way in which the directive is invoked. Notice that the value is: “AECM”. These letters stand for:

  • A : Attribute
  • E : Element
  • C : Class
  • M : Comment

You can use any one of the values by itself, or any combination.

Example # 2:

In Example # 2, we have four snippets of HTML. In each case, we demonstrate a different way to invoke our custom Angular.js directive.

First, as an attribute of the HTML element. Notice how the attribute has no value. In our case, the mere presence of the attribute signals to Angular that our custom directive should be invoked.

Second, as an element. Although there is no such thing as a “ui-widget” HTML tag, Angular will recognize this element and invoke our custom directive.

Third, as a CSS class of the element.

Fourth, as a comment. This approach may seem a bit odd, but you can, in fact, trigger your custom Angular.js directive via an HTML comment.

HERE IS THE LINK TO THE WORKING EXAMPLE FOR THIS ARTICLE: http://examples.kevinchisholm.com/angular/directives/basics/html/part-iii.html

Summary

In this article, we learned about the “restrict” property of the object returned by an Angular directive. We discussed the four possible values for this property, and how each case differs.

Getting Started with Angular. 1.x Custom Directives – Part II – The “replace” property

Angular

Angular.js LogoLearn how your Angular.js directive’s “replace” property determines how it is rendered in the DOM

In the first part of this series: “Getting Started with Angular.js Custom Directives – Part I“, we learned the absolute basics of how to create a custom Angular.js directive. In that article, we learned how to create an Angular module, and then call that module’s “directive” method, which takes a function as its second argument. In that function we returned an object with a “template” property, which contained HTML that would become the actual directive, once injected into the DOM.

In this article, we will learn about the “replace” property, which is a member of the object returned by the directive method. This property is a Boolean, so it has two possible values: true and false. When false, your directive’s HTML is injected into the DOM as a sibling of whatever content is already there. When true, your directive completely replaces the element.

Example # 1A:

In Example # 1A, we have HTML that invokes two Angular directives: “ui-widget-replace” and “ui-widget-no-replace”. Both DIVs look are empty and other than the slight variation in the directive name, they look identical.

Example # 1B:

In Example # 1B, we have the JavaScript that defines these two directives. The “uiWidgetNoReplace” directive has its “replace” property set to: “false”. As a result, the widget that is rendered in the DOM is a child element of the element that invoked the widget (i.e. the element with the “ui-widget-no-replace” attribute). The “uiWidgetReplace” directive has its “replace” property set to: “true”. As a result, the widget that is rendered in the DOM REPLACES the element that invoked the widget. In other words: the element with the “ui-widget-no-replace” attribute is replaced by the widget.

Example # 1C:

In Example # 1C, we see the result of our HTML and JavaScript. The first element completely wraps the widget markup, whereas the second element is the widget (i.e. the widget has completely replaced the markup that declared the ui-widget directive).

This result can be verified when you look at the link for the working example. The element with the attribute: “ui-widget-no-replace” has a blue border, and the element with the attribute: “ui-widget-replace” has a red border. Also, you’ll notice that the first widget is has an inner box with a yellow border. This is because there is a parent-child relationship going on here; because the “replace” property’s value is false, the widget is injected into the DOM as a child of the element that invoked the directive. You can view the page source and examine the CSS to see how this style has been applied.

IMPORTANT: Note that we actually create three modules: “myModNoReplace“, “myModReplace“, and “myMod“. The “myMod” module is the main component used in the page, and it declares the modules: “myModNoReplace” and “myModReplace” as dependencies. Module dependencies is a topic that is beyond the scope of this article, and will be covered in a future post. Just know that in order to have multiple modules used in a page, you’ll need to follow this kind of pattern.

HERE IS THE LINK FOR THIS ARTICLE’S WORKING EXAMPLE:

 http://examples.kevinchisholm.com/angular/directives/basics/html/part-ii.html

Summary

In this article, we learned about the “replace” property. This boolean value allows you to determine whether or not the HTML that makes up your custom directive will completely replace the element that declares our directive, or make it a child element.

Getting Started with Angular 1.x Custom Directives – Part I – Introduction

Angular

Angular.js Logo
Learn how to create your own Angular.js directive (it’s much easier than you think!)

It’s hard to imagine any kind of interaction with Angular that does not involve directives. Angular directives allow you to super-charge your HTML, or even create your own tags.

While there is certainly a generous helping of built-in Angular directives, you don’t have to be satisfied with what comes in the box. You can create your own Angular directives. Not only that, but the way your directive is invoked, what it does, and how it works is completely up to you. Because of the kind of abstraction Angular provides, you are limited only by your imagination.

In this article, we will learn how to create our own Angular directive. This is a fairly deep topic, with plenty of detailed discussions to jump into, many of which will be covered in upcoming editions of this series. For this article, we will focus on the core syntax needed to create a directive and have it render something in the DOM.

Example # 1A

In Example # 1A, we create an angular module named: “widgetApp”, and assign it to the variable “myMod”. The syntax is pretty simple: You call the module method of the angular object, passing it two arguments. The first argument is a string, which is the name by which this module will be known by other modules. What is this means is that if this module is to be considered a dependency by one or more other modules, this string is the name by which those modules will call your new module. The second argument is an array. This array can contain one or more dependencies. If your directive will have no dependencies, you can leave this array empty, but it must be there (i.e., you can’t omit the array).

Example # 1B

In Example # 1B, we have created a custom directive by calling the angular.module’s “directive” method. The first argument is a string: the directive’s external name; that is, this is the name by which you will refer to your directive in the DOM.

The second argument is a function. This function is where we will do the work required to create the directive. Notice that the function returns an object. While this object is empty in our example, it is required. So, even though we return an empty object, we are ok (but you must return an object).

While this directive effectively does nothing, the syntax is correct and there will be no errors on page load. But since our directive has no actual functionality, we will need to put a bit more effort into this.

Example # 2

In Example # 2, we have made a small addition to the anonymous function that is passed to the angular.module’s “directive” method: the object that we return now has one property: “template”. This “template” property’s value is a string of HTML that will be injected into the DOM.

This could be considered the bare minimum needed for a directive that actually renders in the DOM: You return an object that has a “template” property. There is still not too much going on here. Our custom “uiWidget” directive simply adds a DIV element to whichever element calls the directive, and the text of that DIV is: “This is a Widget”.

HERE IS THE WORKING CODE EXAMPLE LINK FOR EXAMPLE # 2: http://examples.kevinchisholm.com/angular/directives/basics/html/part-i.html

Hey Kevin, isn’t creating a custom Angular directive supposed to be a bit more exciting than this?

While injecting “This is a Widget” into the DOM is not a particularly eventful outcome here, the areas we covered are important. Any custom directive you create in the future will follow this exact same pattern. The are many more properties that can be members of the return object, and there is a tremendous amount of power and flexibility available when creating a directive. But remember: as you learn more about custom directives in Angular, every concept covered in this article will still apply.

Summary

In this article we learned the absolute basics about how to create a custom Angular.js directive. Although we barely scratched the surface, we did cover the critical details needed in order to create a directive that actually renders somethign in the DOM. We learned how to create an Anuglar module, and then use that module’s “directive” method to create the directive. We also discussed how the directive is created in a function, and how that function must return an object. That object’s “template” property will contain the HTML that will be rendered in the page.

Angular.js Basics: Routes Part III: Creating a Default Route (version 1.0.8)

Angular

Anuglar.js route

Learn how to create a default route in your Angular single-page app.

In Part II of this series: “Angular.js Basics: Routes Part II: Partials“, we learned how to leverage partials in order to decouple our HTML from the associated controllers. This not only proved to be fairly simple, but it also helps to keep our JavaScript code easier to manage and allows us to create HTML templates that can support a higher degree of complexity.

But in the previous example, when our page loaded, the element with the ngView directive was empty by default. So, the user was required to click a link in order for us to display any content provided by a partial.

In this article, we will learn about a new method of the $routeProvider object that allows us to tell Angular which partial to inject into the DOM when the base page loads.

Two things to note: 1) This article is specific to Angular 1.0.8.   2) The example code that follows leverages code from Part II of this series: “Angular.js Basics: Routes Part II: Partials“. For the sake of brevity, I won’t review much of what we learned in the previous article in great detail. If you are completely new to the idea of Angular Routes, I highly recommend you read Parts I and II of this series, and then return here.

You can download a working version of this code here: https://github.com/kevinchisholm/angular-1.0.8-default-route

The JavaScript file with the code samples you see below can be found in the file: www/js/myApp.js

Configuring your routes

Example # 1

In Example # 1, we re-visit the function expression: configFunction. You may recognize the two calls to $routeProvider.when(). These let angular know how we want it to handle requests to the routes “/hello” and “/goodbye”. In both cases, I’ve omitted the properties of the object that makes up the second argument to that method call, just to keep the example code to a minimum (these details were covered in Part I and Part II of this series).

The otherwise method

What follows those two calls is the .otherwise() method of the $routeProvider object. This method tells Angular what to do if the current request does not match any of the ones specified by the one or more calls we have made to the $routeProvider.when() method.

This is quite a useful feature. It allows us to continue to leverage an Angular partial that will be injected into the DOM by default. A typical scenario for this would be some kind of “home” page. Since the examples provided in this series are focused around the routes “/hello” and “/goodbye”, I decided that when neither route has been requested, I’d like to show the message “Hello!”. I’ve leveraged the same partial file: “message.html”, but the inline anonymous function that is assigned to the “controller” property sets the value of $scope.message” to “Welcome!”. The end result is that when you load the base page (i.e. part-3.html), the default message is “Welcome!”.

Example # 2

In Example # 2, we have added two hyperlinks to our navigation component: “Home” and “Bad Route”. The “Home” link simply requests an unspecified route: “#/”, which displays the default content “Welcome!”. We have specified this in the controller that is a property of the object passed to the $routeProvider.otherwise() method.

 

There is also a link named “Bad Route”, which requests the route: “/badroute”. Since we have not told Angular what to do when this route is requested, the details provided in our call to the $routeProvider.otherwise() method tells Angular to also display the default content: “Hello!”. But a subtle problem we have is the hash. In this case, the URL in the address bar will show: “#/badroute”, even though Angular does as we ask, and displays the default content. The problem here is that we are giving the user an opportunity to deep-link this URL, even though it is an un handled route. We need to fix this.

the redirect-to property

Example # 3

In Example # 3, we have added a new property to the object that is passed to the $routeProvider.otherwise() method: “redirectTo”. This tells Angular that when a route that we have not specified is requested, then in addition to using the specified partial and controller, it should re-direct the requested route to the “root” of our application. We could also specify another valid route, for example “/login”, etc. In this case, we simply want the address bar to show the root of the app. This way, when the user requests a route that is un handled, that request fails gracefully.

Example # 4

In Example # 4, we have the full code for our working example.

View and test the full working example code

HERE IS THE LINK FOR THE FULL WORKIG EXAMPLE: http://examples.kevinchisholm.com/javascript/angular/routes/part-3.html

How to Demo: In the blue box, you’ll notice two hyperlinks: “Hello” and “Goodbye”. Click either one of those links. When you click either link, you’ll notice that the appropriate HTML is injected into the DOM on the right side of the page. Note as well that in your browser’s address bar, “#hello” and “#goodbye” are appended to the URL. This is Angular’s way of providing support for deep-linking. The web page you are on never refreshes, but the hash portion of the URL changes.

Differences in the code

The main difference between this example and the same one from Part # 2 of our series is our use of a default route. When the page initially loads, the message “Welcome!” is displayed. The reason why this happens is: we have specified that message in our call to the $routeProvider.otherwise() method. Also, if you click the link: “Bad Route”, the default route is displayed as well. From Angular’s perspective, it is the exact same scenario: the user has requested a route that has not been specified, so our default route is used.

Summary

In this article, we learned how to create a default Angular.js route. While covering this topic, we focused on the the $routeProvider.otherwise method, which tells Angular how to handle a request for a route that has not been specified by a call to the $routeProvider.when() method. We also discussed the importance of the “redirectTo” property, which tells Angular to redirect to a route that has been properly configured, which makes for a better user experience.

here are some Helpful Links for the $routeProvider.otherwise method

http://docs.angularjs.org/api/ngRoute.$routeProvider

https://www.bitcast.io/b/getting-started-with-angularjs?v=angularjs-routeprovider-api

http://vxtindia.com/blog/8-tips-for-angular-js-beginners/

Angular.js Basics: Routes Part II: Partials

Angular

Angular.js LogoLearn how to use partial templates in your Angular single-page app.

In the first article of this series: “Angular.js Basics: Routes Part I,” we learned how Angular can intercept a hyperlink click, and inject HTML into the DOM. Accomplishing this is surprisingly straightforward because Angular provides a great deal of abstraction with regard to preventing a full-page refresh, DOM manipulation, and deep-linking via the hash.

In that previous post, the HTML that we injected into the DOM was a string that was assigned to the “template” property of the object passed to the $routeProvider.when() method. While this makes it easy to accomplish our task, it is not optimal because we are mixing with JavaScript. Also, a real-world scenario might require markup significantly more robust than the simple one-line string we use (i.e. <h1>{{message}}</h1>). What we need is the ability to leverage HTML that is separate from our JavaScript code, and could be hundreds, even thousands of lines of markup. Most importantly, our JS controller should have no concern for the markup we use; its only job is to be told where it is, and then inject it into the DOM.

An Angular partial is simply an HTML file. The main difference between this and a full-fledged web page is that the partial contains only the HTML we need. There is no need for a !DOCTYPE declaration, HTML, HEAD or BODY elements. The HTML in this file will be injected into the current web page, so only the markup that makes-up the actual component is needed.

Note: The example code that follows leverages code from Part I of this series: “Angular.js Basics: Routes Part I”. For the sake of brevity, I won’t review much of what we learned in the previous article in great detail. If you are completely new to the idea of Angular Routes, I highly recommend you read that article first, and then return here.

Example # 1

In Example # 1, we have the entire contents of the file message.html. This file sits in the same folder as our web page. As you can see, it contains only two lines of HTML: an H1 tag and a paragraph tag. There is also a set of double-curly-braces in the paragraph tag. As per our discussion in the last article, this is a placeholder for the “message” property of the $scope object to which this element is bound.

Example # 2

In Example # 2, we have our call to the $routeProvider.when() method. As per the previous article’s discussion, this method takes two arguments: the path that we want Angular to respond to, and an object that tells Angular how to handle this request.

The code in Example # 2 is virtually identical from that of the previous article with one exception: Instead of using a “template” property, we are now using a property named “templateUrl”. What this tells Angular is:

When the user requests “/hello”, do not actually direct the browser to that path.
Load the file “message.html” via ajax, and inject it into the DOM
In “message.html”, replace {{message}} with the value of $scope.message

While all of this occurs in virtually milliseconds, it is important to note that these steps are, in fact, executed by Angular.

Example # 3

In Example # 3, we have made the same change to the $routeProvider.when() method call for the path “/goodbye”.

Example # 4

HERE IS THE LINK FOR FULL WORKING EXAMPLE: http://examples.kevinchisholm.com/javascript/angular/routes/part-2.html

How to Demo: In the blue box, you’ll notice two hyperlinks: “Hello” and “Goodbye”. Click either one of those links. When you click either link, you’ll notice that the appropriate HTML is injected into the DOM on the right side of the page. Note as well that in your browser’s address bar, “#hello” and “#goodbye” are appended to the URL. This is Angular’s way of providing support for deep-linking. The web page you are on never refreshes, but the hash portion of the URL changes.

The main difference between this example and the same one from Part 1 of our series is our use of partials. Instead of hard-coding an HTML string in our JavaScript controller by assigning it to the ‘template” property, we specify a “templateUrl” property and assign a value that points to an HTML file containing only the markup we need.

Summary

In this article, we learned how to leverage Angular partials. Instead of hard-coding some HTML in our JavaScript file, we tell Angular where to find an HTML file that contains the markup we need. The main advantage here is the ability to decouple our JavaScript from the presentation code. And the HTML files that comprise our partials can be as large or complex as we like.

Helpful Links for Angular Partials

http://docs.angularjs.org/tutorial/step_07

http://onehungrymind.com/building-a-website-with-angularjs-routes-and-partials/

Angular.js Basics: Routes Part I

Angular

Learn how to spin-up an AJAX-driven single-page app by leveraging Angular.s Routes

Single-page applications have become a common project for many front-end web developers. The key components to any such endeavor is the ability to intercept hyperlinks, the updating of the DOM without actually refreshing the page, and support for deep-linking.

Anyone who has attempted even the most basic single-page application knows that managing this kind of interaction on the client-side can be tedious. Angular.js provides a significant level of abstraction when it comes to these kinds of tasks. In a few dozen lines of code, you can quite easily spin-up an AJAX-driven single-page app by leveraging Routes & Views.

Example # 1

In Example # 1, we have added the ng-app directive to the BODY tag. The value is “mainRouter”, which means there must be an Angular module by that name available. We will create this module shortly.

Example # 2

In Example # 2, we have two hyperlinks. Note that the values provided for each element’s HREF attribute are preceded by a hash. This allows Angular to intercept the hyperlink, process the request and prevent the page from following the URL (which would result in an error).

Example # 3

In Example # 3, we have an empty element with an ng-view directive. This is the element into which Angular will inject the HTML templates that we specify.

Example # 4

In Example # 4, we have created an Angular module. This is done by assigning a variable to the return value of a call to the angular.module() method. This method takes two arguments: the name of our module as a string (required), and an array of dependencies (optional). Although the second parameter is optional, because these dependencies are provided via an array, if you do not specify any dependencies, you must still include an empty array.

Example # 5

In Example # 5, we configure our router module by calling it the config() method. This method takes an array as an argument. The first element of the array is the $routeProvider object (which we will use shortly), and the name of a function that will execute our configuration code. It is perfectly acceptable (and quite common) to provide an inline anonymous function for the second parameter. I have specified a function expression instead, simply to keep the example code straightforward and easy to understand.

Example # 6

In Example # 6, we have a function named configFunction(). This function expression is passed to the config() method of our myRouter module. It takes the $routeProvider object as its sole argument. The real action takes place as we make a call to the $routeProvide’s when() method. This method expects two arguments: the URL to watch for, and an object. The properties of that object allow us to tell Angular a number of things about what should happen when the specified URL is requested by the user.

The specified URL is not a fully-qualified web address that starts with “http://”. Instead, we specify a path that is relative to the current page. The general approach is that this path should resemble a RESTful API address.

Examples:

  • http://www.some-domain.com/users (would return a list of users)
  • http://www.some-domain.com/users/1 (would return the user with the ID of “1”)
  • http://www.some-domain.com/users/add (would allow you to add a user)
  • http://www.some-domain.com/users/remove (would allow you to remove a user)
  • Etc…

A discussion of RESTful web services is out of the scope of this article. If you are not familiar with that topic, there are a few links at the bottom of this page that you might find helpful.

In the case of Example # 6, we have told Angular that when the user clicks a link that points to: “/hello”, two things should happen:

  1. The element with the ngView directive should have the HTML string assigned to the “template” property injected into it (i.e.<h1>{{message}}</h1>)
  2. The inline anonymous function that is assigned to the “controller” property should be executed.

A few things to note about these two actions that Angular takes:

In the HTML string that is injected into the element with the ngView directive, there is a set of double-curly-braces. This functions as a client-side template. When the specified HTML is injected into the DOM, the value of the “message” variable is inserted inside of that set of double-curly-braces. That value is provided by the function assigned to the “controller” property of this object passed to the $routeProvide’s when() method. That function takes the $scope object as an argument, and inside of the function, the string: “Hello!” is assigned to the “message” property of the $scope object.

Note: Once again, please note that this function expression could have been defined inline as an anonymous function when we made the call to myRouter.config() in Example # 5. The reason that I chose to break it out like that is because it made it easier to demonstrate the critical pieces of code, while keeping them fairly simple.

Example # 7

In Example # 7, we have added another route: “/goodbye”. So when the user requests that URL, the exact same actions taken in Example # 6 will be performed by Angular, with the only difference being the value of $scope.message: “GoodBye!”.

Example # 8

In Example # 8, we have the full code for our working example.

HERE IS THE LINK FOR OUR FULL WORKING EXAMPLE # 8: http://examples.kevinchisholm.com/javascript/angular/routes/part-1.html

How to Demo: In the blue box, you’ll notice two hyperlinks: “Hello” and “Goodbye”. Click either one of those links. When you click either link, you’ll notice that the appropriate HTML is injected into the DOM on the right side of the page. Note, as well, that in your browser’s address bar, “#hello” and “#goodbye” are appended to the URL. This is Angular’s way of providing support for deep-linking. The web page you are on never refreshes, but the hash portion of the URL changes. If you were to copy and paste http://examples.kevinchisholm.com/javascript/angular/routes/part-1.html#/hello or http://examples.kevinchisholm.com/javascript/angular/routes/part-1.html#/goodbye into another browser, your single-page app would “link” to that desired behavior. What is really happening is that Angular is intercepting any request that comes after the hash, and taking the actions that we specified in Examples # 6 and # 7. If you were to remove the hash from either URL, you would receive an error because the URL http://examples.kevinchisholm.com/javascript/angular/routes/part-1.html/goodbye is not valid.

Summary

In this article, we discussed Angular.js routes, a powerful feature that allows you to create fully-functioning single-page web apps with minimal effort. We talked about how to create an Angular module, configure that module, and call the $routeProvider.when() method in order to tell Angular how to intercept specific URL requests without refreshing the page, and inject the appropriate HTML into the DOM. We also discussed how this feature is based on RESTful URL syntax.

Helpful Links for Angular.js Routes and RESTful Web services

Angular.js Routes

http://docs.angularjs.org/api/ngRoute.$route

http://docs.angularjs.org/api/ngRoute

http://viralpatel.net/blogs/angularjs-routing-and-views-tutorial-with-example/

RESTful Web services

 

http://searchsoa.techtarget.com/definition/REST

http://www.ibm.com/developerworks/webservices/library/ws-restful/

Angular 1.x Data-Binding Basics: the ng-model Directive (Part III)

Angular

Although the Angular ng-model directive creates a privately-scoped object for an element, any descendants of that element also have access to that object.

In the previous article of this series: “Getting Started With Angular.js: Data-Binding Basics With the ng-model Directive (Part II)” we demonstrated how two HTML elements with their own unique ng-controller values can reference the same-named data value, yet access completely different data. The main purpose of that article was to demonstrate how each individual ng-controller directive creates a privately-scoped $scope object.

In this article, we will demonstrate how each privately-scoped $scope object inherits from the next ancestor with an ng-model directive, all the way up the DOM tree.

There are three very important native JavaScript concepts at play here:

  1. scope
  2. context
  3. object.prototype

Although a thorough discussion of any of these three topics is more than can adequately be covered here, it is important to note that they all come into play. I’ll point them where appropriate.

Example # 1

In Example # 1, we have an element with the class “parent”. It wraps the two “children” elements that we used in the previous article. Notice that the ng-model directive has a value of: “myData.parent”. This means that this element has a privately-scoped $scope object, with a property “myData”, which is an object, and that object has a property named “parent”. Note as well that the {{myData.parent}} placeholder is bound to the exact same data.

Example # 2

In Example # 2 we have a “child” element. Compared to the HTML from Part II of this article, there are a few changes:

The text box and span.val elements are bound to the data: “myData.left”
We have added two elements that are bound to “myData.parent”.

The reason for adding the second set of data-bound elements is to demonstrate that this “child” elements has access to not only its own privately-scoped data: “myData.left”, but also the “myData” property of the $scope object of it’s next descendant with an ng-model attribute. This is an example of leveraging JavaScript’s prototype object to create inheritance. While it may seem that JavaScript “scope” is driving this kind of parent -> child access to the Angular $scope object, it is, in fact, inheritance through the prototype object.

HERE IS THE JS-FIDDLE.NET LINK FOR EXAMPLE # 2: http://jsfiddle.net/Gfm7Q/

How to Demo: Type anything in the box. You’ll see that when you type in the “parent” text box, both “children” have access to its data, and that updated data is injected into the DOM of each “child” element in real-time. Yet each “child” element has access to its own privately-scoped $scope.myData object (i.e. myData.left and myData.right).

Example # 3 A

Example # 3 B

In Example # 3A, we have a new element: “grandParent”. The exact same concept as the “parent” element applies: this element has an Angular ng-model directive with a value of: “myData.grandParent”, yet its privately-scoped $scope object is inherited by the “parent” object and both “child” objects.

In Example # 3B, we see a snippet of HTML that has been added to the “parent” and “child” elements. The purpose of this HTML is to demonstrate that we can bind DOM elements to data that belongs to ancestor elements.

HERE IS THE JS-FIDDLE.NET LINK FOR EXAMPLE # 3: http://jsfiddle.net/Gfm7Q/1/

How to Demo: Type anything in the text box. You’ll see that when you type in the “Grand Parent” text-box, the “parent” element and both “children” have access to its data, and that updated data is injected into the DOM of each descendant element in real-time. The same goes for the “parent” element. Yet once again, each “child” element has access to its own privately-scoped $scope.myData object (i.e. myData.left and myData.right).

Example # 4

In Example # 4, we have the full HTML for this article’s working code.

Summary

Much like Part I and Part II of this series on Angular.js data-binding, the examples in this article are very simple. The goal was to provide a very basic demonstration of how DOM elements have access to the data that is bound to their ancestors via their ng-model directive. A key concept to focus on is the fact that Angular provides abstraction for this functionality which would require a great deal of code to replicate. Furthermore, this abstraction is application-agnostic, so you can leverage Angular for a wide range of projects. The features provided have no knowledge of how they will be employed. They “just work.”

Helpful Links for Angular $scope Inheritance

https://github.com/angular/angular.js/wiki/Understanding-Scopes

http://www.ramandv.com/blog/angular-js-sharing-data/

http://stackoverflow.com/questions/14232397/scope-inheritance-in-angularjs

http://www.cubicleman.com/2013/03/14/angularjs-and-a-js-prototypal-inheritance-gotcha/

Angular.js Data-Binding Basics: the ng-model Directive (Part II)

Angular

Learn how to use the exact same HTML, yet let Angular bind that markup to different pieces of data.

In Part I of this series: “Getting Started With Angular.js: Data-Binding Basics With the ng-model Directive (Part I),” we covered the absolute basics of data-binding with Angular.js. In that article, we discussed how multiple elements can be bound to the same piece of data, and when that data changes, any elements bound to it are updated.

While this kind of abstraction is incredibly useful and powerful, it is a simple scenario. Having multiple DOM elements that are bound to different pieces of data is probably a more real-world context for a front-end web developer.

In this article, we will learn how to use the exact same piece of HTML yet let Angular bind that markup to different pieces of data.

Example # 1

In Example # 1, we have some very simple HTML. There is an input element, and a paragraph. You will probably notice that this HTML looks a bit unusual. The input element has what looks like an HTML attribute named: “ng-model”. But this is not a standard HTML attribute, it is actually an Angular directive. It specifies the data that this element will be bound to.

The second area where you may notice something unusual is the text: {{myData}} that is inside of the SPAN element with the class: “val”. This functions as a placeholder for some data that is named: “myData”.

The HTML detailed above will be used numerous times in this article’s examples. The main point to stress here, is that this HTML is generic in nature; there are no HTML ID attributes in use, and no data is hard-coded. For this reason, it can be used more than once, exactly as-is, throughout our HTML.

Example # 2

In Example # 2, we have two “child” elements. These simply serve as containers for the code in Example # 1. These elements are almost completely generic. The only thing that differentiates them from each other is the Angular directive: “ng-controller”. They each reference a different controller. There is a reason for this, which will be addressed shortly. Other than the value of the “ng-controller” directive, the HTML of these two elements is identical.

NOTE: If you look at the BODY tag, you will see that this element also has an Angular directive: ng-app (<body ng-app>). This tells Angular that it should manage all elements contained inside of that element.

Example # 3

In Example # 3, we have two functions: “leftController” and “rightController”. You may recognize the names from the two Angular directives mentioned in Example # 2. Controllers allow you to provide private variable scope on a per-element basis. Each element in your application that has an “ng-controller” directive has its own $scope object, which is a variable in a function behind the scenes, which makes it private. Each instance of this object can be extended as-needed. Even though the two functions specified in Example # 3 do absolutely nothing at this point, they are required because the “ng-controller” directive tells Angular: “hey, use this function for this element, in order for it to have its own private $scope object.” So, even if it does nothing, the function must exist globally.

Note: it is highly recommended that you leverage best practices such as name-spacing in order to make your controllers accessible while keeping the global name-space clutter-free. This kind of design pattern is out of the scope of this article, but you can learn more about it in my article: “Using an Immediate Function to Create a Global JavaScript Variable That Has Private Scope.”

Example # 4

In Example # 4, we have placed the HTML from Example # 3 inside of a “child” element. This means that the data referenced by: “myData” is private to the element: div.child.left. When you look at the working code for this example, you’ll see that anything you type in the input field is injected into the DOM.

HERE IS THE JS-FIDDLE.NET LINK FOR EXAMPLE # 4: http://fiddle.jshell.net/Pnwz4/

How to Demo: Type anything in the text box. You’ll see that whatever you type is updated in the element below the text box. Both the text-box and the element that displays the text are bound to the “myData” property of the same object, which has been created by Angular. This object is a private variable, created by the controller: “leftController”.

Example # 5

In Example # 5, we have added a second copy of the input element HTML. Because they both reside within the element with the Angular directive: ng-controller=”leftController”, all references to “myData” point to the same object’s “myData” property.

HERE IS THE JS-FIDDLE.NET LINK FOR EXAMPLE # 5: http://fiddle.jshell.net/Pnwz4/1/

How to Demo: Type anything in either text box. You’ll see that anything you type in either input field is injected into the DOM. Once again, this is because all references to myData point to the same object.

Example # 6

In Example # 6, we have moved the second INPUT element (and associated elements) to a different “child” element, which has its own ng-controller directive. This means that although each INPUT element and client side template references data named: “myData”, they are referencing different data (in each case, “myData” is a property of the $scope object that is a private variable of a different function).

HERE IS THE JS-FIDDLE.NET LINK FOR EXAMPLE # 6: http://fiddle.jshell.net/Pnwz4/2/

How to Demo: Type anything in either text box. You’ll see that only the DOM element that resides in the associated “child” element is updated. This is because each “child” element references a different ng-controller directive, which provides a privately-scoped variable containing the object that holds the “myData” value.

Example # 7:

In Example # 7, we have the complete HTML for this article’s working example. When you type in the text-input of each child element, the text you type is injected into the DOM.

Summary

The purpose of this article was to demonstrate how the exact same HTML can easily be used in more than one place, but access completely different data by leveraging Agular.js. We were able to accomplish this by creating two different container (aka “child”) elements that had different ng-controller directives. Because each Angular controller creates its own privately-scoped $scope object, two pieces of HTML that are both bound to the same-named data actually reference completely different data. While the examples in this article were extremely simple, I hope they provided a way for you to gain a basic understanding of how Angular controllers provide private data scopes for HTML elements with minimal effort on the part of the developer.

The most important concepts discussed here are:

  • Angular.js directives are extensions of HTML, and look / function much like attributes.
  • The ng-controller directive provides a privately-scoped $scope object for an element.
  • When you specify an ng-controller directive for an element, you must be sure to make a function available that matches the value of the ng-controller directive (this can be a function declaration or a function expression).

Helpful Links for the Angular.js $scope object

http://docs.angularjs.org/api/ng.$rootScope.Scope

http://www.ng-newsletter.com/posts/beginner2expert-scopes.html

http://docs.angularjs.org/guide/directive

http://blog.kevinchisholm.com/angular/angular-js-data-binding-basics-the-ng-model-directive-part-i/

Angular 1.x Data-Binding Basics: the ng-model Directive (Part I)

Angular

Grunt.js Logo
Data-binding with Angular.js is surprisingly simple. To get started, you need only specify an ng-model directive.

One of the most common tasks for any JavaScript developer is to inject a value into the DOM. This value can be a variable or the property of an object. When doing so, you need to make a reference to the target element, and then use a native JavaScript or jQuery method to inject that value (e.g. [SOME_ELEMENT].innerHTML or $(SOME_ELEMENT).html() ). But if that value is injected into more than one element, your work grows exponentially. You now have to manage multiple DOM element references, write code that makes the injections, and also code that pays attention to the data you are working with, so that when that data changes, you can update the DOM element(s) that need to know about that update.

Angular.js provides jaw-dropping abstraction that not only takes care of your messy DOM injection & data-management tasks, but does so with a simplicity and elegance that is truly to be admired.

This scenario can quickly spiral into a frustrating mess of nested-callbacks, hard-coded DOM element references and data-handling functions.

One of the main features of Angular is “Directives.” Angular.js directives are extensions of HTML. They look / function much like HTML attributes; each directive is part of the element’s opening HTML tag, and requires a value, which is enclosed in double-quotes. The ng-model directive specifies the name of a piece of data, which one or more elements can be bound to.

Before we get started, we’ll need to let Angular.js know that we want it to manage our web page. We can do this by adding an ng-app directive to the markup that we want managed (or an element on the page that is a descendant of that markup, such as HTML or BODY).

Example # 1

In Example # 1, we see the ng-app directive. This simply tells Angular to manage everything inside of the BODY tag. We could have placed this close to the elements that we actually want Angular so manage, but it is most simple, and not uncommon, to place it in the BODY tag.

Example # 2

In Example # 2, we have a text box (an input that has a type attribute of “text”), and a paragraph. We have provided an ng-model attribute for the input element, and provided a value of “myData”. Behind the scenes, Angular has created an object that is a private variable of a function, given it a property named “myData”, and bound the value of it to this element. Anything that we type into this textbox will become the updated value of the “myData” property, and when that same “myData” property is changed elsewhere, this textbox will reflect that new value. This two-way data-binding is one of the most powerful features of Angular.js. You’ll also notice that in the HTML of Example # 2, there is a set of double-curly braces, with the text “myData” inside of it. This tells Angular that the value of myData should go inside of the double-curly braces, and be updated whenever the value of myData changes. If you click the link below, it will take you to the JsFiddle.net link for the fully working demo of Example # 1’s code.

HERE IS THE JS-FIDDLE.NET LINK FOR EXAMPLE # 2: http://jsfiddle.net/L69aq/

How to Demo: Type anything in the text box. You’ll see that whatever you type is updated in the element below the text box. Both the text-box and the element that displays the text are bound to the “myData” property of the same object, which has been created by Angular.

Example # 3

In Example # 3, we have added a select element to the page. We have included an Angular ng-model directive and specified a value of “myData”. This means that the select element is bound to the exact same data as the two elements in Example # 2’s code.

If you click the link below, it will take you to the JsFiddle.net link for the fully working demo of Example # 3’s code.

HERE IS THE JS-FIDDLE.NET LINK FOR EXAMPLE # 3: http://jsfiddle.net/L69aq/1/

How to Demo: In addition to typing something in the text box, you can now select one of the options from the drop-down box. Now that SELECT element, the text-box, and the element that displays the text are bound to the “myData” property of the same object, which has been created by Angular.

Summary

In this article, we covered the bare-bones basics of data-binding in Angular.js. The key component here is the ng-model directive. We discussed how the ng-model directive creates a property of an object that is a private variable of a function, and bound to any element whose ng-model directive’s value is the same. We also demonstrated that when more than one element’s ng-model directive values are the same, there is a two-way data binding because when one element changes the value of the data, the rest of the elements bound to that data are updated, and vice versa.

This article merely scratches the surface of data-binding in Angular.js, but the hope is that it has provided a foundation upon which you can start to understand the incredibly powerful and elegant JavaScript library.

Helpful Links for Angular.js Data Binding Basics

http://docs.angularjs.org/guide/databinding

http://docs.angularjs.org/api/ng.directive:ngModel

http://en.wikipedia.org/wiki/AngularJS#Two-way_data_binding