Deborah's Developer MindScape






         Tips and Techniques for Web and .NET developers.

Archive for AngularJS

November 25, 2014

Exception Handling in an AngularJS Application

Filed under: AngularJS @ 9:25 am

Wouldn’t it be great if everything always just worked? That we never had a runtime error… That the server-side Web services were always available and worked? But we know that is not the case. Things go wrong.

The most common ways to handle exceptions in an Angular application are:

  • With a JavaScript try/catch block
    • You can add a try/catch block around code that could fail
    • That allows you to catch specific errors and handle them appropriately.
  • You can use the Angular global exception handler
    • Angular has a built-in service, called $exceptionHandler, that catches exceptions
    • By decorating this service, you can tailor it to the needs of your application.
  • When working with promises, you can also add failure or catch functions

This post covers the second option, using the Angular global exception handler.

If you are interested in more information, I cover exception handling in detail in my Pluralsight course: “AngularJS Line of Business Applications“.

image

Decorating $exceptionHandler

Angular provides a built-in global exception handling service called $exceptionHandler. Any uncaught exception is delegated to this service. This service only catches exceptions, not communication errors (such as 404 not found) or syntax errors.

The default implementation of $exceptionHandler logs any exceptions to the browser console. You can change this functionality by decorating the $exceptionHandler service.

Say we wanted to change the default global exception handler to display a message to the user. We could accomplish this by decorating the $exceptionHandler service as shown in the code below:

image

  • Line 14:
    • The above code configures the application with a decorator.
    • The code needs the Angular built-in $provide service, so it is passed as a parameter to the configuration function.
  • Line 15:
    • The $provide service is used internally as part of Angular’s component registration process.
    • The decorator method of this service can intercept requests and provide different or additional functionality.
    • The decorator method takes two parameters:
      • The first parameter is the string name of the service being decorated. In this case, it is the $exceptionHandler service.
      • The second parameter is a min-safe array containing the name of each decorator function parameter and then the decorator function itself.
  • Line 16:
    • The decorator function has a dependency on $delegate. So $delegate is listed in the min-safe array.
    • $delegate provides the original service to the method. This allows you to call the base implementation of that service.
  • Line 17:
    • $delegate is passed as a parameter to the decorator function.
  • Line 18:
    • This method returns a decorated $exceptionHandler service object.
    • The returned function has two parameters: the exception and the cause.
  • Line 19+20:
    • In this example, the code in the returned function replaces the exception message with a custom message.
  • Line 21:
    • Then it uses $delegate to call the base implementation of the service.
    • The base implementation simply logs the error to the console.
  • Line 22
    • Lastly, this code adds an alert to notify the user of the issue.

Now, any time that an unhandled exception occurs, the message is logged to the console (the default behavior) *and* the user is notified with an alert.

You can add anything you need to this function. For example, you may want to add more extensive logging or a more detailed message.

Enjoy!

November 24, 2014

Creating Pretty Tabs with HTML and CSS

Filed under: AngularJS @ 4:31 pm
Tags: , ,

If you are building data entry forms with HTML (using AngularJS or ASP.NET or other technologies), you may find that you need more space than can fit onto one page. In that case, you may want to implement tabs.

In my AngularJS course entitled “AngularJS Line of Business Applications“, I demonstrate how to build data entry forms using tabs. The result looked like this:

image

I also showed a version with styled tabs like this:

image

This blog post details how to change the rectangular tabs from the first image to the more stylized tabs in the second image.

To keep the example simple, we’ll work with just the tabs:

image

The code for the page shown above with the rectangular tabs is as follows:

<!DOCTYPE html>
<html>
<head lang=”en”>
    <meta charset=”UTF-8″>
    <title>Acme Product Management</title>

    <!– Style sheets –>
    <link href=”css/bootstrap.css” rel=”stylesheet”/>
    <link href=”css/app.css” rel=”stylesheet”/>
</head>

<body>
  <div class=”panel panel-primary”>
    <div class=”panel-heading” style=”font-size:large”>
        Acme Product Management
    </div>

    <div class=”panel-body”>
        <div class=”wizard”>
            <a>
                Basic Information
            </a>
            <a>
                Price Details
            </a>
            <a>
                Search Tags
            </a>
        </div>
   </div>

  </div>
</body>

</html>

Notice that the tabs are defined with anchor (<a>) tags. Notice also that this HTML links to two css files:

body {
    background-color: #C6D9F1;
}

.wizard a {
    background: #efefef;
    display: inline-block;
    margin-right: 5px;
    min-width: 150px;
    outline: none;
    padding: 10px 40px 10px;
    position: relative;
    text-decoration: none;
}
.wizard .active {
    background: #007ACC;
    color: #fff;
}

We’ll need to add some additional styles to the app.css file in order to implement the arrow-style tabs as shown below:

image

First, we’ll add a before selector for the anchor tag:

.wizard a:before {
        width: 0;
        height: 0;
        border-top: 20px inset transparent;
        border-bottom: 20px inset transparent;
        border-left: 20px solid #fff;
        position: absolute;
        content: “”;
        top: 0;
        left: 0;
    }

This creates the “cut out” on the left side of the tabs.

Then we’ll add the triangle shaped arrow on the right side of the tabs using an after selector for the anchor tag:

.wizard a:after {
        width: 0;
        height: 0;
        border-top: 20px inset transparent;
        border-bottom: 20px inset transparent;
        border-left: 21px solid #efefef;
        position: absolute;
        content: “”;
        top: 0;
        right: -20px;
        z-index: 2;
    }

Lastly, we want to ignore the “cut out” border on the left side of the first tab and the arrow on the right side of the last tab. This gives us a clean look for the far left and far right of the tab bar:

.wizard a:first-child:before,
.wizard a:last-child:after {
        border: none;
    }

And if you want to round the corners at the far left and far right of the tab bar, you can round them with this:

.wizard a:first-child {
        -webkit-border-radius: 8px 0 0 0px;
        -moz-border-radius: 8px 0 0 0px;
        border-radius: 8px 0 0 0px;
    }

.wizard a:last-child {
        -webkit-border-radius: 0 8px 0px 0;
        -moz-border-radius: 0 8px 0px 0;
        border-radius: 0 8px 0px 0;
    }

Try building this simple page and then adding each css class and running the application to see its effect on the tabs before adding the next css class.

Enjoy!

October 2, 2014

AngularJS: Visualizing Data with Charts

Filed under: AngularJS @ 5:20 pm

Data visualization can help users see patterns in an often overwhelming amount of data. One key technique for visualizing data is to display that data in a set of charts.

image

Because charting is a common requirement, there are JavaScript libraries available for building charts. D3.js is one such library. D3.js is a JavaScript library for manipulating documents based on data. It provides powerful data visualization components. With all of its power and flexibility comes a steep learning curve.

Luckily, you won’t have to learn d3 to build charts with Angular. Angular-charts is a wrapper around basic d3 features for use in Angular. You can use Angular-charts to build pie, bar, line, point, and area charts.

If you want to create charts in your Angular application, try out the charting example on the Angular-charts page.

Or check out the “Visualizing Data with Charts” module in my “AngularJS Line of Business Applications” course.

Enjoy!

October 1, 2014

Angular Talk at Visual Studio Live! in Washington DC on October 7th, 2014

Filed under: AngularJS,Visual Studio @ 5:25 pm

I am very excited to talk about AngularJS at the upcoming Visual Studio Live! conference in Washington DC!

The session is entitled “Build an Angular and Bootstrap Web Application in Visual Studio from the Ground Up“. It is aimed at intermediate level developers that are new to or just getting started with AngularJS. Because this *is* a Visual Studio conference, the sample application is built using a Visual Studio Web Site for the Angular application and ASP.NET Web API for the back-end Web service. (Though the talk only walks through the Angular code, not the Web API code … we only have 75 minutes!)

If you are looking for the code for this session, you can find it on github here.

If you are not familiar with github, just click the Download ZIP button in the bottom right to download a zip file containing the code.

image

If you are interested in more information about Angular, check out my latest Pluralsight course: “AngularJS Line of Business Applications”. The sample application for the course is built from scratch using WebStorm, but could be created using Visual Studio.

Enjoy!

August 1, 2014

Boldly Code With Us: Preview of Visual Studio Live! Washington, D.C.

Filed under: AngularJS,General,Visual Studio @ 4:09 pm

Earlier this week I presented a preview of my two sessions for the Visual Studio Live! conference coming up in Washington DC on October 6-9, 2014. My two sessions at the conference are:

  • New IDE and Editor Features in Visual Studio 2013
  • Build an Angular and Bootstrap Web Application in Visual Studio from the Ground Up

In the preview, I outlined some of the new IDE and Editor features and then selected one to demonstrate.

I then provided an introduction to AngularJS, specifically what it is and why you may want to use it for development of client-side Web applications.

If you are interested, the recording of this preview presentation is posted here.

Enjoy!

PS circleCheck out my Pluralsight courses!
July 30, 2014

Learn AngularJS at VSLive in Washington DC

Filed under: AngularJS,General @ 5:24 pm

If you’ve ever been to Washington DC you know that it is filled with pomp and circumstance. It seems every activity is wrapped in ceremony.

That may be fun when touring history … but no so much when you are writing a Web application. When building an application you want to get work done, not spend lots of time on ritual and setup and ceremony.

AngularJS is all about simplification … getting rid of ritual and ceremony. With AngularJS …

  • You don’t have to write code to navigate the document object model (DOM) as you do with JQuery. No need to id everything and find the Ids on the page.
  • You don’t have to write any code that maps properties from your model to the UI and back again … AngularJS provides automatic two-way data binding.
  • You can easily call a Web service such as Web API.
  • You can write clean Web code!

Join me in Washington DC October 6-9 and learn how to use Angular to build your next Web application.

Use this promo code: DCSPK13 or click on the image below for more information or to register. You’ll save $400!

DCSPK13

Enjoy!

July 23, 2014

AngularJS: 101* Ways to Create a Controller (* actually 8)

Filed under: AngularJS @ 6:53 pm

OK, there aren’t really 101 ways to create an AngularJS controller. But when you are first learning and looking at examples, it may seem that there are 101 ways!

This post walks through the most common ways to create an Angular controller. The goal here is to put the different techniques in one place for you to compare and contrast.

NOTE: In all of these examples, the JavaScript code for the controller is added directly to the HTML file so it is easy for you to try it out. In a “real” application, you would add the code for the controller to a separate .js file (as covered in a future post). You can use the techniques presented below regardless of where the controller code resides.

The UI used in all of these examples is a movie hunter application that displays a list of movies. In all cases, the result appears like this:

image

The html is:

<!DOCTYPE html>
<html>
<head lang=”en”>
<meta charset=”UTF-8″>
<title>InStep Movie Hunter</title>

<!– Use the Content Delivery Network (CDN) –>
<script
 
src=”http://ajax.googleapis.com/ajax/libs/angularjs/1.2.17/angular.min.js”>
</script>
<link
href=
http://netdna.bootstrapcdn.com/bootstrap/3.1.1/css/bootstrap.min.css
rel=”stylesheet” />
</head>

<body ng-app>

    <div class=”row  bg-primary”>
        <div class=”col-md-6″>Title</div>
        <div class=”col-md-2″>Director</div>
        <div class=”col-md-2″>Release Date</div>
        <div class=”col-md-2″>Rating</div>
    </div>

    <div class=”row” ng-controller=”SearchByMovieCtrl>
        <div class=”col-md-6″>{{movie.title}}</div>
        <div class=”col-md-2″>{{movie.director}}</div>
        <div class=”col-md-2″>{{movie.date}}</div>
        <div class=”col-md-2″>{{movie.mpaa}}</div>

    </div>

    <script>
        <!—The controller code goes here –>
    </script>

</body>
</html>

Notice two things:

  1. The ng-app attribute on the body tag in the HTML.
    • This attribute is required to identify the page as an Angular application.
    • This attribute currently has no value assigned to it.
    • This attribute is normally defined on the html or body tag.
  2. The ng-controller attribute on the div tag in the HTML.
    • This attribute defines the name of the controller function associated with a piece of the html.
    • This attribute is set to “SearchByMovieCtrl”, which is the name of the controller function.
    • The html tags that are child tags of this div tag (highlighted in green) have access to any of the controller function’s objects and methods. In this example, the controller provides a movie object.

NOTE: The elements and attributes in the html that begin with “ng-” are called Angular directives.

The code for any of the following controllers can be inserted within the script tag as per the highlighted comment above.

#1: Controller with a Function Declaration

A controller is simply a function. In this example, a function is declared within the script tags shown in the html above:

function SearchByMovieCtrl($scope) {
        $scope.movie = {
            title: ‘The Fellowship of the Ring’,
            director: ‘Jackson’,
            date: ‘2001-12-19′,
            mpaa: ‘PG-13′
        }
    }

The browser determines which controller function to call based on the ng-controller attribute defined within the html. So the name defined in the ng-controller attribute must match the name of the function. The name is “SearchByMovieCtrl” in this case.

When this function is called, Angular passes in a parameter called $scope. Anything that the controller function adds to the $scope is accessible to all of the html elements that are within the element containing the ng-controller attribute. (These are highlighted in green above.)

This controller function simply adds a movie object to the $scope. That movie object is then available to the html elements within the div tag containing the ng-controller attribute. The movie object properties can be displayed in the html using the Angular expression syntax {{}} as shown in the html.

To see the effect of the ng-controller attribute, try moving the {{movie.mpaa}} line outside of the outer div element and see what happens.

(The html will then display {{movie.mpaa}} instead of PG-13.)

This style of controller is quick to create, but is problematic in that it adds the function to the global namespace. This means it is available to any other code executing within the browser window. As the page becomes more complex, you could have problems with name collisions. (One function x overrides another function x because they have the same name.)

#2: Controller with a Function Expression

This technique is similar to the prior example, but defines the controller in a function expression instead of a function declaration. (If you are not sure of the difference between a function declaration and function expression, check out this post.)

    var SearchByMovieCtrl = function ($scope) {
        $scope.movie = {
            title: ‘The Fellowship of the Ring’,
            director: ‘Jackson’,
            date: ‘2001-12-19′,
            mpaa: ‘PG-13′
        }
    }

Notice that this code assigns the function to a variable called “SearchByMovieCtrl”. In this case, the function itself has no name, so it’s referred to as an anonymous function. But it could have a name without impacting how this controller works.

This technique has the same pros and cons as the prior technique. But now instead of putting a function on the global namespace, it is defining a variable on the global namespace.

#3: Controller with a Module

If you have been learning Angular, you know that Angular prefers that you define a module for your Angular application. The module is the component that ties all of the other Angular application components together.

After defining a module, you define a controller and register it with the module. That way the html can find the controller without needing to put the controller function in the global namespace of the application.

    var app = angular.module(“movieHunter”, []);

    app.controller(“SearchByMovieCtrl”,
            function ($scope) {
                $scope.movie = {
                    title: ‘The Fellowship of the Ring’,
                    director: ‘Jackson’,
                    date: ‘2001-12-19′,
                    mpaa: ‘PG-13′
                }
            });

The first line of this example defines an Angular module named “movieHunter”. The module setter has two parameters:

  • The first parameter is the name of the module.
  • The second parameter is an array of dependencies to other modules/components. For a demo application as simple as this one, there are not dependencies so the array is empty.

The second line then registers the controller with that module. The registration method takes two parameters:

  • The string name of the controller (SearchByMoveCtrl)
  • The function that is the controller. In this case, it is an anonymous function.

This example (and all of the examples that follow) requires one additional change to the original HTML. The body tag needs to be changed as follows:

<body ng-app=”movieHunter>

When the ng-app directive is not associated with a module, Angular looks for the controller in the global namespace for the page.

When the ng-app directive is assigned to a module name, Angular will then look for the controller registered with the module when it sees the ng-controller tag.

This technique is a much better than the prior two in that it uses the module. Angular much prefers to use a module to manage the components of the application. Plus it keeps the function out of the global namespace.

#4 Controller with a Module and Function Declaration

Some developers don’t like to put an entire function inside of a parameter of a method call. So you can instead define a function and pass a reference to it to the registration function as shown below.

var app = angular.module(“movieHunter”, []);

function SearchByMovieCtrl($scope) {
    $scope.movie = {
        title: ‘The Fellowship of the Ring’,
        director: ‘Jackson’,
        date: ‘2001-12-19′,
        mpaa: ‘PG-13′
    }
};

app.controller(“SearchByMovieCtrl”,
        SearchByMovieCtrl);

The first line of this example defines the Angular module called “movieHunter” as in the prior example. The second line defines the controller function. The last line registers the controller with the module by referencing the function in the second parameter.

The problem with this approach is that we again have the SearchByMovieCtrl in the global namespace.

#5 Controller with a Module and Function Expression

This technique is similar to #4 above, but with a function expression. (If you are not sure of the difference between a function declaration and function expression, check out this post.)

var app = angular.module(“movieHunter”, []);

var SearchByMovieCtrl = function ($scope) {
    $scope.movie = {
        title: ‘The Fellowship of the Ring’,
        director: ‘Jackson’,
        date: ‘2001-12-19′,
        mpaa: ‘PG-13′
    }
};

app.controller(“SearchByMovieCtrl”,
        SearchByMovieCtrl);

The first line of this example defines the Angular module called “movieHunter” as in the prior two examples. The second line defines the controller function and assigns it to a variable. The last line registers the controller with the module by referencing the function in the second parameter.

This approach puts the SearchByMovieCtrl variable in the global namespace.

#6 Controller with a Module and Minification-Safe Array

To improve performance when an application first starts up, many developers minify their files. This minification process removes excess spaces and changes function parameter names to a single character. This makes the files smaller so they download more quickly from the Web server to the client browser.

The problem with minifying an Angular application is that Angular expects the parameter names to be a specific name, not a minified name. For example, if you replaced the $scope variable in any of these examples with another variable name the code would not work.

To prevent the minification process from shortening the parameter names, you can provide the list of parameter names as strings as the second parameter to the controller registration function as shown below.

When you change the second parameter to a list (or technically speaking an array), you still need to pass the name of the controller (or the entire controller  function) as the last entry in the array. This is shown below.

var app = angular.module(“movieHunter”, []);

function SearchByMovieCtrl($scope) {
    $scope.movie = {
        title: ‘The Fellowship of the Ring’,
        director: ‘Jackson’,
        date: ‘2001-12-19′,
        mpaa: ‘PG-13′
    }
};

app.controller(“SearchByMovieCtrl”,
        [“$scope”,SearchByMovieCtrl]);

The second parameter of the controller registration is now an array containing:

  • The string name of each controller function parameter.
  • The reference to the function (or the function itself) as the last entry in the array.

This approach works the same as the prior approaches. The only difference is that the code will continue to work correctly after it has been minified. If you never plan to minify the files (and expect no one else on the team or in operations to minify the files) then this array is not needed.

#7 “Controller as” Syntax

This option is new in version 1.2 of Angular, so you won’t see it in any older posts.

The “Controller as” syntax requires several changes both to the original html and to the controller function itself:

  • First, the ng-controller attribute value in the html is changed to include the “as” keyword:

<div class=”row” ng-controller=”SearchByMovieCtrl as vm>

  • Second, the references to the controller objects in the html need to be changed to use the “controller as” alias.

    <div class=”row” ng-controller=”SearchByMovieCtrl as vm“>
        <div class=”col-md-6″>{{vm.movie.title}}</div>
        <div class=”col-md-2″>{{vm.movie.director}}</div>
        <div class=”col-md-2″>{{vm.movie.date}}</div>
        <div class=”col-md-2″>{{vm.movie.mpaa}}</div>
    </div>

NOTE: vm in this example stands for “view/model”. This is commonly what is used here because the controller is thought of as the connection between the view and the model or “view/model”.

  • Lastly, the $scope is no longer required as a parameter to the controller function. It is still available to the function, but implied. Instead of using “$scope”, the code instead adds objects and methods to “this”.

var app = angular.module(“movieHunter”, []);

var SearchByMovieCtrl = function () {
    this.movie = {
        title: ‘The Fellowship of the Ring’,
        director: ‘Jackson’,
        date: ‘2001-12-19′,
        mpaa: ‘PG-13′
    }
};

app.controller(“SearchByMovieCtrl”,
        SearchByMovieCtrl);

The “controller as” syntax is clean and easy. But the explicit $scope syntax may be easier to understand when first learning.

#8 Controller with IIFE

A key issue with several of the above techniques was concern about the global namespace. Any variable or function declared external to a function becomes part of the global namespace of the application. This can be a problem, especially as the application gets larger.

One way to mitigate this problem is to use an Immediately Invoked Function Expression or IIFE (pronounced “iffy”). The idea of an IIFE is that if variables and functions are declared within a function, then the variables and functions are local to that function and not part of the global namespace.

You can wrap *any* of the above examples in an IIFE. Below is the code for example #7 wrapped in an IIFE:

(function () {
    var app = angular.module(“movieHunter”, []);

    var SearchByMovieCtrl = function () {
        this.movie = {
            title: ‘The Fellowship of the Ring’,
            director: ‘Jackson’,
            date: ‘2001-12-19′,
            mpaa: ‘PG-13′
        }
    };

    app.controller(“SearchByMovieCtrl”,
            SearchByMovieCtrl);
})();

For more information on IIFE by the person that coined the term, see this post.

You can use an IIFE with any of the above techniques to minimize pollution of your global namespace.

There you have it … 101 …  ok … 8 … ways to create a controller.

Enjoy!

PS circleCheck out my Pluralsight courses!

P.S. I am currently working on an Angular course for Pluralsight entitled “AngularJS Line of Business Applications”. Please comment below if you have suggestions for content that is not covered well elsewhere. Thanks!

July 10, 2014

Angular ng-grid Quick Tip

Filed under: AngularJS @ 12:47 pm

I added a grid page to one of my applications using ng-grid (http://angular-ui.github.io/ng-grid/) to provide a quick way to update sets of prices.

But it wasn’t working correctly. If I edited one price and clicked to the next row, the edit box on the prior row did not close. After editing three prices the grid looked like this:

image

And looking at the output, I found this:

Exception was thrown at line 3494, column 17 in http://localhost:3950/js/ng-grid-2.0.11.debug.js
0x800a01b6 – JavaScript runtime error: Object doesn’t support property or method ‘focus’

After spending the better part of yesterday afternoon trying to figure out what was wrong, I gave up and decided to start fresh again this morning. (Always a good option when you are stuck.)

As part of my debugging, I had found a working example here: http://plnkr.co/edit/hy6Evh?p=preview

So I downloaded that example and started to modify it to match my existing code. Was it the routing? No. Was it the other loaded controls like the date picker or masked edit? No.

It turned out to be the ORDER of the script files in my index.html.

To see the problem in action, try this: http://plnkr.co/edit/p4iLdfoYydZ9LKU312zK?p=preview

This is the *same* as the prior Plunk except for the order of the script files.

For the ng-grid to work correctly, the jquery library must be listed BEFORE Angular.

<script src=”js/jquery.js”></script>
<script src=”js/angular.js”></script>

Now it looks much better:

image

Hope this tip helps others!

Enjoy!

PS circleCheck out my Pluralsight courses!
June 20, 2014

ACM Seminar: Getting Started with AngularJS

Filed under: AngularJS @ 8:57 pm

 

My business partner, Jerry, and I are presenting a full day session on AngularJS to the Association for Computing Machinery (ACM) on Saturday, June 21st 2014. Should be fun!

Check out this link for more information.

The code for this seminar is here.

NOTE: To make this code easy to execute and try out, the calls to a Web Service are commented out and the data is instead hard-coded into the controllers.

  • The movies controller has a hard-coded list of movies.
  • The movie detail controller has ONE hard-coded movie. So no matter which movie you select to detail, only the ONE hard-coded movie is displayed.
  • Same for the actors controller and actor details controller.

Enjoy!

March 7, 2014

AngularJS in Visual Studio: Data Binding

Filed under: AngularJS,Data Binding,Visual Studio @ 12:15 pm
!function(d,s,id){var js,fjs=d.getElementsByTagName(s)[0],p=/^http:/.test(d.location)?’http':’https';if(!d.getElementById(id)){js=d.createElement(s);js.id=id;js.src=p+'://platform.twitter.com/widgets.js';fjs.parentNode.insertBefore(js,fjs);}}(document, ‘script’, ‘twitter-wjs’);

This is a continuation of the World’s Simplest AngularJS Example in Visual Studio post. This post adds simple data binding to the example.

Most .NET developers understand data binding from Windows Forms, Web Forms, or XAML.

For example, in Windows Forms you can bind a LastNameTextbox control’s Text property to a LastName property of a Customer class (or LastName field in a data source). When the form displays, the Textbox is automatically populated. If the user changes the contents of the Textbox, the property (or field) is automatically updated.

image

Angular provides this same type of two-way data binding. It automatically synchronizes HTML elements with data properties.

The key to data binding with Angular is the ng-Model directive. The ng-Model directive binds HTML elements to a property. If no property exists, the property will be created implicitly. We’ll use that default functionality to perform data binding without any real properties for this simple example.

Let’s try some very simple data binding:

<!DOCTYPE html>
<html xmlns=”
http://www.w3.org/1999/xhtml”>
<head>
    <title>Acme Customer Management</title>
</head>
<body ng-app>
    <p>Customer Name: <input type=”text” 
                             ng-model=”customerName” /></p>
    <div>{{customerName}} Orders as of {{ “2014-01-31″}} </div>

    <script src=”Scripts/angular.js”></script>
</body>
</html>

  • The above code sets the ng-model directive as an attribute on the input tag.
  • The value of the ng-model directive is the name of the property to which this input tag is bound. In this case, the property is named “customerName”.
    • This binds the input tag to the defined property.
    • As the user types into the input box, the customerName property is automatically updated.
    • This property is not defined anywhere, so Angular creates it implicitly.
  • The div tag displays the value of the property by including it in double curly braces.
    • Double-curly braces define a “binding” and can contain any Angular expression.
    • In this case, the expression is just the property name.
    • So the value of the property will appear where the binding is defined.
  • As the user enters text into the input box, that text is immediately displayed in the div tag.

Run it, and you get:

image

Enter some text, and it appears as follows:

image

We’ll see lots more about binding once we connect to some data.

Enjoy!

PS circle


Check out my Pluralsight courses!

Next Page »

© 2014 Deborah's Developer MindScape   Provided by WPMU DEV -The WordPress Experts   Hosted by Microsoft MVPs