Get Started with Angular

AngularSometimes the best way to learn a new technology is to start using it -- a little at a time. In this series of articles, I will show you how to use Angular in a step-by-step manner. You start with a simple example of adding Angular to a project and creating an Angular module and controller. Once you have the controller, you will see how to expose data so it can be bound to UI elements on your HTML page.

Adding Angular to a Project

Create a new ASP.NET Web Application project, or load one of your existing web projects. Right mouse click on the web project, not the solution, and choose Manage NuGet Packages… from the menu. You will then see a screen that looks like Figure 1.

 

Figure 1: Use the Manag NuGet Packages menu to add Angular to your project.

Click on the Browse tab (Figure 2) and type in AngularJS and press the enter key. Select AngularJS.Core from the list and click on the Install button. Visual Studio will add a few files to your project and you may now use Angular in your project.

Figure 2: Select AngularJS.Core from the list.

If you look in the \Scripts folder you should see a few files that start with “angular”. The only one you will use on your page for purposes of learning Angular is the angular.min.js.

Create a Test Page

Add a simple HTML page that you can use to test a few concepts of Angular. Right-mouse click on the project and select Add | HTML Page. Type in the name AngularSample01 and click the OK button. Drag and drop the Content\bootstrap.min.css into the <head> element on the page. Drag and drop the following script files before the </body> tag; Scripts\jquery-VER#.min.js, Scripts\bootstrap.min.js, and Scripts/angular.min.js. Type in the rest of the HTML shown below.

<!DOCTYPE html>
<html>
<head>
  <title>Angular Sample</title>
  <meta charset="utf-8" />
  <link href="Content/bootstrap.min.css" rel="stylesheet" />
</head>
<body>
  <div class="container">
    <div class="form-group">
      <label for="ProductName">Product Name</label>
      <input type="text" class="form-control" />
    </div>
    <div class="row">
      <div class="col-xs-12">
        <label for="ProductName">Product Name Entered</label>
        <p class="form-control-static"></p>
      </div>
    </div>
  </div>
  <script src="Scripts/jquery-1.10.2.min.js"></script>
  <script src="Scripts/bootstrap.min.js"></script>
  <script src="Scripts/angular.min.js"></script>
</body>
</html>

Create Angular Module

Right mouse click on the Scripts folder and select Add | JavaScript File from the menu. Type in app in the text box and click the OK button. In this new JavaScript file, add the following code.

(function () {
  'use strict';
  angular.module('ptcApp', []);
})();

The above code uses an Immediately Invoked Function Expression (IIFE) to access the angular framework and create a new module. The new module name is passed as a string in the first parameter of the module function. In this case, that module name is ‘ptcApp’. Feel free to name this whatever you want, for whatever is appropriate for your application. The second parameter is used to list any dependencies you wish to use in this module. The empty array signifies that there are no dependencies in this case.

Think of an Angular module as a namespace in C#. It is a wrapper, or container, for other things you create within the module. One thing you create within a module is a controller in which you define functions and variables to use from your HTML page.

Create a Controller

In a typical web page you either display data or get data from input fields. With Angular you typically use data binding to accomplish both of these tasks. To use data binding, you first must have some variable names as the source of your bindings. We create these variable names within a “controller” that you define in another JavaScript file. Angular uses the Model View Controller (MVC) design pattern. A controller is responsible for managing the data binding between the model (properties of the $scope variable) and the view (the HTML page).

Right mouse click on the Scripts folder in your project and select Add | JavaScript File from the menu. Type in productController in the text box and click the OK button. In this new JavaScript file, add the following code.

1  (function () {
2    'use strict';
3  
4    angular.module('ptcApp')
5      .controller('PTCController', PTCController);
6  
7    function PTCController($scope) {
8      var vm = $scope;
9  
10     // Expose a 'product' object
11     vm.product = {
12      ProductName: 'Pluralsight Subscription'
13     };
14   }
15 })();

Line 1 starts an IIFE. On lines 4 and 5 you reference the module named ‘ptcApp’ you created earlier. Chain the controller() function to declare your intention to use a controller with the name of ‘PTCController’. The second parameter to the controller function is a reference to a function callback named PTCController. Lines 7 through 14 is the PTCController function declaration that Angular calls when it needs to reference something from the HTML page. 

Angular passes to the controller function a parameter named $scope. The $scope variable is an object created by Angular to provide a mechanism to glue the directives you create on an HTML page with the variables defined within your controller. A good practice is to immediately assign $scope to your own variable name as you see on line 8. Many people use the variable name ‘vm’ because we think of $scope as a View Model object.

On lines 11 thru 13 you create a variable named ‘product’ that is an object literal with 1 property named ProductName. You assign a hard-coded value to this property. To display this property’s value in and input field on the HTML page, use an Angular directive called ‘ng-model’ (also written as ngModel). The value of this ng-model attribute is the name of the property defined on the $scope.

<input type="text" 
       ng-model="product.ProductName" 
       class="form-control" />

The ng-model directive says to look at the current scope of the HTML page and attempt to locate the variable named ‘product’ within that scope. Then access the ProductName property to display its value within the input field. The question is, how does the ng-model directive know the scope it is contained within, and the controller to use? That is explained in the next section.

Define the Module and Controller for a Page

So far, all you have done is to create an HTML page and a couple of JavaScript files. How do you hook them together? We need to use two more Angular directives; ng-app and ng-controller. The first step is to drag the two .js files onto your HTML page. Be sure to place them below the script tag for angular.

<script src="Scripts/angular.min.js"></script>
<script src="Scripts/app.js"></script>
<script src="Scripts/productController.js"></script>

Modify the <html> tag of your HTML page so it looks like the following:

<html ng-app="ptcApp">

Make sure the ng-app (also written as ngApp) directive has the exact same name as what you defined in the app.js file. In this case that name is ‘ptcApp’. This directive instructs Angular that it should look for a module declared with the name of ‘ptcApp’ and assign the scope of that module around all of the DOM elements within the <html> tag. The second directive, ng-controller (also written as ngController), you place on the <body> tag of your HTML page.

<body ng-controller="PTCController">

This directive gives scope to everything within the <body> tag on this HTML page to the controller function PTCController. You do not need to place this directive on the <body> tag. You may place this directive on a <div> tag around just one specific area of the page. In this way you could have different controllers for different parts of a page.

Data Binding

Now that you have the scope defined, you bind the ‘product’ variable defined in your controller function to one or more HTML elements. Open up your HTML page and modify the Product text box to look like the following:

<input type="text" 
       ng-model="product.ProductName" 
       class="form-control" />

When binding to <input> elements in HTML you use the ng-model directive. This directive enables two-way data binding. If you modify the value of the ProductName property in JavaScript code, the UI will be immediately updated with the new value. If the user modifies the input field with a new value, the ProductName property is updated immediately with the new value entered.

To show this in action, let’s bind the <p> tag to the product.ProductName property. Since you are not dealing with an <input> element, use the data binding syntax of curly braces as shown below:

<label for="ProductName">Product Name Entered</label>
<p class="form-control-static">{{product.ProductName}}</p>

Use this data binding syntax when you are simply displaying data on the HTML page. You typically see this kind of data binding when building an HTML table or a <select> list.

Run the Page

If you have followed along with this article, you can now run this HTML page. You should see something that looks similar to Figure 3. If you type into the input field, you will see the value in the <p> tag updated immediately.


Figure 3: Data binding makes working with data a breeze.

Summary

In this blog post you learned how to add Angular to an MVC project. You learned about modules, controllers and scope. You also created a variable on the scope variable and learned to bind that variable’s value to a couple of elements on the HTML page. These are the basics of using Angular. In the next series of blog posts, we will explore a lot of cool things you can do with this powerful framework.

More Angular Blog Posts

PDSA has www.pluralsight.com courses on Angular. Check out The Journey from MVC to Angular.

Sample Code

You can download the code for this sample at www.pdsa.com/downloads. Choose the category “PDSA Blog”, then locate the sample PDSA Blog Sample: Get Started with Angular.

Sitefinity - More than Content Management

Cloud Sitefinity is more than just content management. You can use it as a complete platform upon which you can build your own line-of-business web application. Here is just a sampling of what you can do with Sitefinity.

  • Customize Sitefinity master page and control templates
  • Create business application features using MVC widgets
  • Integrate Web API with business application features
  • Customize notification email templates with application-specific information
  • Create custom Sitefinity membership and role providers
  • Integrate active directory users and roles into Sitefinity

  • PDSA has successfully customized Sitefinity for many clients. Read one case study here. Contact us today to learn how we can assist you with your Sitefinity project.

    Read many other reasons in our special report at http://www.pdsa.com/Download/SpecialReports/SR-Sitefinity.pdf

    Why Move to the Cloud

    Cloud Cloud computing has gained incredible momentum over the last several years, and with good reason. As companies start looking at the cost of purchasing new hardware and new software licenses, they quickly realize that this investment is not very economical compared to paying a monthly subscription that covers all their needs. When you move your applications, databases and websites into the cloud, hardware is no longer a concern, and you are just a click away from being on the latest version of software or operating system at no additional cost. Read many other reasons in our special report at http://www.pdsa.com/Download/SpecialReports/SR-Cloud.pdf

    What Makes a Developer Excellent?

    Successful Developers What makes some programmers stand above the rest? How can some programmers create wildly new and useful algorithms while others struggle? What are the important traits that make an exceptional programmer? Your answers will be different depending on whether you are a programmer--OR someone who hires and manages them. In this article, I'll explore some of these questions and pose answers that will help make you a better –and more valuable—programmer.  If you hire programmers, you'll know a good one when you see them.

    Read our special report entitled Good Developers Versus Exceptional.

    Check out all of our Special Reports here.

    Locate an Address using Geocoding

    Very popular in many web and mobile applications today is the ability to locate an address on a map. In this post you will learn to use the google maps API to do just this. Create a new HTML page and add jQuery and Bootstrap to the page so it resembles the HTML shown below.

    <!DOCTYPE html>
    <html>
    <head>
      <title>Geocode Sample</title>
      <link href="../Content/bootstrap.min.css" rel="stylesheet" />
      <style>
        #theMap {
          width: 100%;
          height: 600px;
        }
      </style>
    </head>
    <body>
      <div class="container">
        <div class="row">
          <div class="col-xs-12">
            <h1>Geocode Address</h1>
          </div>
        </div>
        <div class="form-group">
          <label for="address">Address</label>
          <input id="address"
                 type="text"
                 class="form-control"
                 value="17852 17th Street, Tustin CA 92780" />
        </div>
        <div class="form-group">
          <button id="search"
                  class="btn btn-sm btn-primary"
                  onclick="controller.searchClick();">
            Search
          </button>
        </div>
        <div class="row">
          <div class="col-xs-6">
            <div class="form-group">
              <label for="lat">Latitude</label>
              <input id="lat"
                     type="number"
                     class="form-control"
                     value="0" />
            </div>
          </div>
          <div class="col-xs-6">
            <div class="form-group">
              <label for="long">Longitude</label>
              <input id="long"
                     type="number"
                     class="form-control"
                     value="0" />
            </div>
          </div>
        </div>
        <div class="row">
          <div class="col-xs-12">
            <div id="theMap"></div>
          </div>
        </div>
      </div>
      <script src="../scripts/jquery-1.11.0.min.js"></script>
      <script src="../scripts/bootstrap.min.js"></script>
    </body>
    </html>


    Notice the additional <style> tag in the <head>. This is used to style the <div> tag that will display the google map. <div> tags are defined with a height of zero, so if you don't add at least a height, your map will not show up.

    Add the following script tag for the google map API just below the bootstrap.min.js script tag.

    <script src="https://maps.googleapis.com/maps/api/js?v=3&sensor=false&libraries=geometry"
            type="text/javascript">
    </script>


    Create a JavaScript Closure

    Define a JavaScript closure to hold all of the logic for our page. The code snippet below shows the overall structure of the closure without the details of each function. We will cover the details a little later. Notice that this closure is assigned to a variable named 'controller'. You will see this referenced in the onclick attribute of the Search button shown above in the HTML.

    <script>
      var controller = (function () {
        // Declare Private Variables
        var map = null;
        var location = null;
        var lat = 0;
        var long = 0;
        var address = '';
        var mapId = 'theMap';
        var markerIcon = 'http://maps.google.com/mapfiles/ms/icons/blue-dot.png';
        // ************************************
        // Private Functions
        // ************************************
        // Display messages
        function display(msg) {
          alert(msg);
        }
        // Search for address
        function searchForAddress() {
        }
        // Initialize map
        function initMap() {
        }
        // Add marker to map
        function setMarker(pos, title) {
        }
        
        // Update any UI elements
        function updateUI() {
        }
        // ************************************
        // Public Functions
        // ************************************
        return {
          searchClick: function () {
            address = $("#address").val();
            searchForAddress();
          },
          setMapId: function (id) {
            mapId = id;
          },
          setMarkerIcon: function (icon) {
            markerIcon = icon;
          }
        };
      })();
    </script>


    Private Variables

    At the top of the closure is where you declare private variables needed for geocoding and to hold values retrieved from the web page or to put back onto the web page.

    'map' - a reference to the google map object. 

    'location' - a LatLng object. 

    'lat' and 'long' - numeric values that hold the latitude and longitude respectively.

    'address' - a street address to locate. 

    'mapId' - the id of the <div> where you wish to place the map. 

    'markerIcon' - the icon to use for the map marker.


    Private Functions

    Private functions defined in the closure are used to do searching, create the google map object, set map markers and update the web page UI with any data.

    display() - display any messages to the user.

    searchForAddress() - search for the street address and if found will set the 'lat' and 'long' variables, display the map, and display a marker on the map at the location of the found address.

    initMap() - creates the google map and displays it on the web page.

    setMarker() - adds a marker to the map at the specified coordinates.

    updateUI() - update any fields or other elements on your page.


    Public Functions

    Public functions are created so you can call private functions from your web page.

    searchClick() - get the address to search for from the input and calls the searchForAddress() function.

    setMapId() - allows you to change the id of the element to place your map upon.

    setMarkerIcon() - allows you to change the icon to use as your map marker.


    The searchForAddress() Function

    The searchForAddress() function locates a physical address and sets the 'lat' and 'long' variables so you can display a marker of where the address is located on a map. An instance of a google.maps.Geocoder object has methods for performing geocoding. Call the geocode() function of the Geocoder object passing in an object literal with the string 'address' and the actual address to locate. This is an asynchronous call, so you need to supply a call back function. This function needs two parameters; 'result' and 'status'. You check the 'status' to ensure that you received an OK. If you receive an OK status, check the 'results' array at element 0 to get the address information.

    Within the 'results[0]' element is a geometry object which contains a location. Call the lat() function to retrieve the latitude for the address and set the 'lat' variable. Call the lng() function to retrieve the longitude for the address and set the 'long' variables. Once these variables are set, call the initMap() function to create a map using these coordinates as the center point. Call the setMarker() function to place a map on the specified coordinates. Finally, call updateUI() to display the latitude and longitude in the appropriate fields on the web page. There are several other status codes that can be returned from the geocode() function, so you should give the user an appropriate messages based on that status.

    function searchForAddress() {
      var geocoder = new google.maps.Geocoder;
      if (address.length > 0) {
        geocoder.geocode({ 'address': address }, function (results, status) {
          switch (status) {
            case google.maps.GeocoderStatus.OK:
              if (results[0]) {
                // Get latitude
                lat = results[0].geometry.location.lat();
                // Get longitude
                long = results[0].geometry.location.lng();
                // Initialize the map
                initMap();
                // Set marker on map
                setMarker(location, address);
                // Update the UI
                updateUI();
              }
              else {
                display("Could not locate address.");
              }
              break;
            case google.maps.GeocoderStatus.ZERO_RESULTS:
              display("No such address found.");
              break;
            case google.maps.GeocoderStatus.OVER_QUERY_LIMIT:
              display("Query limit has been exceeded.");
              break;
            case google.maps.GeocoderStatus.REQUEST_DENIED:
              display("Query request was denied.");
              break;
            case google.maps.GeocoderStatus.INVALID_REQUEST:
              display("Query request was invalid.");
              break;
            default:
              display("Unknown status: " + status);
              break;
          }
        });
      }
      else {
        display("Please enter an address.")
      }
    }


    The initMap() Function

    The initMap() function creates a new LatLng object using the variables 'lat' and 'long' in the closure. Create an object literal with the properties 'center', 'zoom', and 'mapTypeId'. Set 'center' to the new LatLng object. Set 'zoom' to the size of the map you wish to display. You may need to play with this number a bit to see what size you prefer. The 'mapTypeId' is a constant defined by google. You can choose the most common option, ROADMAP, or set it to SATELLITE, TERRAIN or HYBRID.

    function initMap() {
      location = new google.maps.LatLng(lat, long);
      var options = {
        center: location,
        zoom: 15,
        mapTypeId: google.maps.MapTypeId.ROADMAP
      };
      map = new google.maps.Map(document.getElementById(mapId), options);
    }


    The setMarker() Function

    After the map is drawn, add a map marker by calling the setMarker() function. This function creates a Marker object by passing in an object literal with the properties 'position', 'map', and 'title'. The 'position' is the LatLng object you created in initMap(). 'map' is the map object you created in initMap(). The title can be anything you want to appear when you hover over the map marker.

    function setMarker(pos, title) {
      var marker = new google.maps.Marker({
        position: pos,
        map: map,
        title: title
      });
      marker.setIcon(markerIcon);
    }


    The updateUI Function

    I prefer to keep all updates to my UI in as few functions as possible. So, I create a updateUI() function that updates any fields on my page with the values from my private variables.

    function updateUI() {
      $("#lat").val(lat);
      $("#long").val(long);
    }


    Summary

    In this blog post you learned how to map a physical address to a latitude and longitude and display that address on a map. You can get more information at https://developers.google.com/maps/. If you would like help with any #geocoding projects, please call #PDSAinc at (714) 734-9792 to discuss your project.


    Locate your IoT Device using Geocoding

    Many applications today have a need to show the user where they are, direct them to a specific location, or maybe show the location of a certain asset. In a #IoT application we are currently developing, we have a device that sends us its latitude and longitude. From this we want to display this information on a map so our user can quickly locate that asset. Performing this task is very easy using the google maps API (#googlemaps). Let's take a look at the small amount of code you need to add to any HTML page.

    First add a <div> tag at the location on your page where you wish to place the map.

    <div id="theMap"></div>

    Now add a little styling to the map

    <style>
      #theMap {
        width: 600px;
        height: 600px;
      }
    </style>

    Next, include the appropriate script file for the google API.

    <script src="http://maps.google.com/maps/api/js?sensor=true"
            type="text/javascript">
    </script>

    All you need now are your latitude and longitude from your IoT device, which I have hard coded in the code below.

    (function () {
      // Private Variables
      var map = null;
      var lat = 33.758432;
      var long = -117.820738;
      var mapID = "theMap";   // Initialize the map   initMap();   function initMap() {   var startLoc = new google.maps.LatLng(lat, long);     var mapOptions = {       center: startLoc,       zoom: 15,       mapTypeId: google.maps.MapTypeId.ROADMAP     };     map = new google.maps.Map(document.getElementById(mapID), mapOptions);   } })();

    The function initMap() first gets a LatLng object from the google maps API. You could use a LatLng literal object instead, but I want to reuse this LatLng object later in my code to place a marker, so I will create the object. Next you create a map options object that tells the center point using your LatLng object. You may specify a zoom level that you want. You will have to play with this number to get the zoom level you want as the default. There are a few different types of maps you can display. The most common one is the road map, which is specified by using the ROADMAP constant. Finally you send a reference to the <div> element and the map options object to the Map() function of the google API. This will draw the map into your <div> element.

    If you run the page, you should see a map appear over the city of Tustin, CA. This is where the PDSA offices are located. If you wish to place a map marker over the location, add the following code after the call to the google.maps.Map() function.

    var marker = new google.maps.Marker({
      position: startLoc,
      map: map,
      title: 'PDSA'
    }); marker.setIcon('http://maps.google.com/mapfiles/ms/icons/blue-dot.png');

    That is all there is to starting to use the google API geolocation services in your application. You can get more information at https://developers.google.com/maps/.


    As always, if you need help implementing any of the concepts in our posts, please feel free to reach out to #PDSAinc and we will be happy to help.