Angular 1.x Basics: Manually Boot-Strapping Your Application (Part II)

Angular

Angular JSOne of the advantages of manually boot-strapping Angular.js is the ability to take care of any setup-tasks that you want completed before the DOM is parsed.

In the previous article: “Angular.js Basics: Manually Boot-Strapping Your Application (Part I)“, we learned how simple it is to manually boot-strap Angular. In that example, our HTML was hard-coded in the page, including the {{myData}} template. We manually boot-strapped Angular by clicking a button, which in-turn, executed our boot-strapping code.

This was fine for a basic proof-of-concept, but having the {{myData}} template render on page load is not acceptable. For this article, our goal will be to inject some HTML into the DOM, and then boot-strap Angular, building upon our code from Part I of this series.

Example # 1:

In Example # 1, we leverage the angular.element() method, passing it a reference to the document object. We then chain the ready() method to the return value of the angular.element() method, passing it an anonymous function. This tells Angular that when the document is in a “ready” state, the anonymous function passed to the .ready() method should be executed.

Example # 2:

In Example # 2, we have added a few things:

1) The base DOM element that will contain HTML, managed by Angular (i.e. DIV#main)

2) A call to the angular.element() method, which sets up an anonymous function that will be called when the document is read

3) The bootAngular() function, which we have re-used from Part I of this series.

HERE IS THE JSFIDDLE LINK FOR EXAMPLE # 2: http://jsfiddle.net/T3jcx/

When you view the JsFiddle.net link for Example # 2, you’ll notice… well you’ll notice nothing! This is because there are no DOM elements for Angular to interact with. Although our code does, in fact, boot-strap Angular, Angular parses the DOM, but finds no “ng” directives or data-bound templates.

Example # 3A:

In Example # 3A, we have a string that contains HTML that will be injected into the page. The actual HTML is virtually identical to the markup from Part I of this series, but instead of hard-coding it in the actual web-page, it is contained in a string, which is a JavaScript variable: “template”.

Example # 3B:

In Example # 3B, we leverage the .run() method of our module. This is a method that we did not create, Angular provides it because our module (“myMod”), was created by Angular. We pass an anonymous function to the .run() method and this function takes the $rootScope object as an argument. A detailed discussion of the $rootScope object is beyond the scope of this article. But, it is helpful to know that it is the top-level container for all data managed by our module.

Inside of the anonymous function passed to the .run() method, we do two things:

1) Set the value of $rootScope.myData

2) Inject our HTML into the DOM

The most important thing to know is that when our module is instantiated, it’s .run() method is executed. So, we have specified what we want done when our module starts, which is to set the value of $rootScope.myData, and inject our HTML into the page.

Example # 4:

In Example # 4, we have the completed code. Comments have been added to help you follow along.

HERE IS THE JSFIDDLE LINK FOR EXAMPLE # 4: http://jsfiddle.net/w6Y3n/

How to Demo This Code:

Although it feels as if the HTML that contains the text box and {{myData}} template render on page load, they do not. Things happen pretty quickly here, but now that we have our completed code, and you have the JsFiddle.net link so that you can see the example code in action, let’s run-down what happens.

1) When the page loads, the BODY tag contains an empty DIV element with the ID: “main”

2) In the SCRIPT block, we create a variable named: “template”, which is a string containing HTML that will be injected into the page

3) We create the function: bootAngular(), which contains the code that boot-straps Angular

4) The angular.element() method is called, and then the ready() method is chained to the return value, and we execute the bootAngular() function as a result

5) Inside the bootAngular() function, we create an Angular module “myApp;” we call the myMod.run() method, which sets the value of $rootScope.myData, and then our HTML is injected into the DOM

6) We call the angular.bootstrap() method, which instantiates the myApp module, telling it to manage the BODY element in our page.

Summary:

In this article, we took a slightly more sophisticated approach to manually boot-strapping Angular. We leveraged the angular.element() method, which allows us to tell Angular to wait until the document is ready before proceeding, by using the .ready() method. We also learned about the [MODULE].fun() method, which provides a way to specify code that will execute when our module is instantiated. In the next article of this series, we will learn how to boot-strap multiple areas of the DOM manually.

 

Angular.js Basics: Manually Boot-Strapping Your Application (Part I)

Angular

Although setting an ng-app directive on the HTML element makes for quick and easy Angular.js boot-strapping, there may be times when you’ll want to initiate that process manually.

In an earlier blog post, we learned that boot-strapping an Angular Application is as simple as setting an ng-app directive on the HTML element, and then adding a script tag that will inject Angular.js into the page. Technically, we can set the ng-app directive on any element in the page, and we can even set it on multiple elements and provide the appropriate values for each directive, so that Angular knows which module will control which portion of the page.

While this kind of declarative architecture is both elegant and efficient, there may be times when you want to boot-strap Angular.js yourself. A common scenario might be one in which you want to have the initial web page render with no application-specific markup, inject the appropriate markup into the page, and then boot the application. This allows you to run any pre-application logic you need, and even decide on which markup to preset first, based on variable such as the URL path, the presence of a cookie, or some other condition.

While some might argue that this could be better handled by Angular Routes and Views, keep in mind that we are talking about tasks we want to run before Angular is even boot-strapped. So, the challenge is: “How can I boot-strap Angular.js manually?”

Fortunately, the process of boot-strapping Angular manually is fairly simple.

The Two Basic Steps Are:

1) Create an Angular module

2) Call the angular.bootstrap method, passing it two arguments: A) An element that the module will manage, and B) The name of the module that will manage that element (and all descendant elements)

Example # 1:

In Example # 1, we have the base HTML for our examples. For the sake of brevity, we are focusing on only the DOM elements that interest us. I’ll assume you understand that there are elements such as DOCTYPE, HTML HEAD and BODY, which make up a basic web page, as well as SCRIPT tags that inject jQuery and Angular, etc.

HERE IS THE JSFIDDLE LINK FOR EXAMPLE # 1: http://jsfiddle.net/mzcxQ/

When you view the JsFiddle.net link for Example # 1, you’ll see that although Angular was injected into the page using a SCRIPT tag in the HEAD section, it has not booted yet. This is evidenced by the fact that the {{myData}} template has not been parsed, and the actual curly braces appear in the page, which is not the desired effect. What we should see is an empty text box, and as you type in the textbox, whatever you have typed appears where the {{myData}} template is.

Example # 2:

In Example # 2, we create a variable named “myMod”. This variable will hold a new Angular module. We create the module by calling the angular.module method, and passing it two arguments:

A) The name of our module: ‘myApp’

B) An empty array

The empty array could be used for dependency injection, which is beyond the scope of this article. We don’t have any dependencies, but even so, the empty array is required.

Example # 3:

In Example # 3, we call the angular.bootstrap method, passing it two arguments:

A) The DOM element which will be managed by a module

B) The name of the module that will manage that element

In this example, we kept it simple and passed a reference to the BODY element, using jQuery. We could have specified the HTML element, or a more deeply-nested element in our page such as $(‘main .appContainer’), for example.

Example # 4:

In Example # 4, we have finally boot-strapped our Angular application. The combination of these two expressions was all that was needed in order to get Angular to start managing our DOM. To help emphasize the demonstration, we will wrap all of our code in a function, and execute that function when the button in our markup is executed.

Example # 5:

 

In Example # 5, we have wrapped all of our code in a function named: “bootAngular()”. We then created a click-event handler for the button in our markup (i.e. #bootAngular). When this button is clicked, the function bootAngular() is executed, and the button is disabled. When the bootAngular() function executes, our Angular boot-strapping code is executed, and Angular is boot-strapped.

HERE IS THE JSFIDDLE LINK FOR EXAMPLE # 5: http://jsfiddle.net/rvM4B/

How to demo this code:

When you view the JsFiddle.net link for Example # 2, you’ll notice that on page load, the {{myData}} template appears in the page. This is not what we want. It happens because while Angular has been injected into the page, it has not been boot-strapped. When you click the button labled: “Boot Angular”, our code executes, Anuglar is boot-strapped, the {{myData}} template disappears, and as we type in the text-box, whatever we type appears where the {{myData}} template was displayed. This is because Angular now manages that portion of the page. It has created a data-binding to the data: “myData” because it parsed the ng-model directive in the HTML, and whenever that data changes, the {{myData}} template is updated accordingly.

Summary:

In this article we learned how to manually boot-strap Angular. We learned how to create an Angular module, and then pass that module to the angular.bootstrap() method. We also learned that we pass a reference to the DOM element which we would like Angular to manage. This simple two-step process is all that is needed to boot-strap Angular. While the example provided is very basic, it illustrates the simplicity with which Angular can be manually boot-strapped.

 

 

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