AngularJS Tutorial

AngularJS TutorialWelcome to my AngularJS Tutorial. In this tutorial I clear up all of the jargon in AngularJS through a ton of examples. We’ll cover the Model View Controller pattern and how it works with AngularJS. I’ll then provide examples that explain AngularJS Modules, Directives, Scope, and Expressions.

Beyond those topics I’ll also cover dependency injection, ng-app, ng-init, ng-controller, ng-model, event handling, data-ng-bind, ng-repeat, multiple views, multiple controllers, ng-cloak, $index, $first, $last, $middle, $even, $odd, ng-repeat-start, ng-repeat-end, ng-include, ng-switch, ng-switch-when, ng-disabled, ng-hide, ng-show, ng-class and much more.

If you like videos like this please consider supporting me on my Patreon page.

[googleplusone]

Code From the Video

angulartut.html

<!doctype html>

<!-- Define the ng-app parameter in the root element so AngularJS
knows where to begin compiling. app1 is the module name and is referenced
in the JS file we will create -->

<!-- ng-init is a directive that initializes application data by assigning
variable values -->
<html ng-app="app1" ng-init="person = {fName: 'Derek', lName: 'Banas'};
  capitals = [{city: 'Montgomery', state: 'Alabama'}, {city: 'Juneau', state: 'Alaska'}, {city: 'Phoenix', state: 'Arizona'}]">
  <head>
    <title>AngularJS Tutorial</title>
  </head>
  <body>

    <!-- Adds a controller that the Angular module will control.
    The view is the div element and all that it contains. The $scope
    component is used to provide data to the view. -->
    <div ng-controller="ctrl1">
      <span>Values:</span>

      <!-- Define 2 elements that will be bound to the first and
      second values in the scope using the ng-model directive. If
      either value changes here it will change in the scope and
      vice versa -->
      <input type="text" ng-model="first" />
      <input type="text" ng-model="second" />

      <!-- Bind a click on this button to the function updateValue
      using ng-click -->
      <button ng-click="updateValue()">Sum</button>
      <br><br>

      <!-- Displays the Scope value of calculation in the expression-->
      {{calculation}}

      <!-- You can perform calculations in expressions -->
      <p>5 + 5 = {{5+5}}</p>

      <!-- Expressions bind data to HTML as well -->
      <p>Your first value is {{first}}</p>

      <!-- You can do the same with ng-bind -->
      <p>Your second value is
        <span data-ng-bind="second"></span>
      </p>

      <!-- Strings can be built in expressions -->
      <p>{{person.fName + " " + person.lName}} you entered {{first + " and " + second}}</p>

      <!-- ng-repeat cycles through a collection -->
      <ul>
        <li ng-repeat = "capital in capitals">
          {{ 'City: ' + capital.city + ', State: ' + capital.state}}
        </li>
      </ul>

    </div>

    <!-- Load the AngularJS library -->
    <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.4.9/angular.min.js"></script>

    <!-- Load the JS Module -->
    <script src="js/exam1.js"></script>
  </body>
  </html>

exam1.js

/*
---------- Components of an AngularJS Application ----------

AngularJS provides a front end framework based on the MVC model. It is built on top of JavaScript and JQuery. With MVC the Model represents the data source, the View is the rendered page, and the Controller handles communication between both of them. By structuring your page this way your code is easier to maintain, easier to update and makes for more readable code.

AngularJS uses modules which represent the components used in your application. Using modules makes it easy to reuse your code in many applications.

Web pages are normally manipulated by working with the DOM object in JavaScript and JQuery. AngularJS allows you to extend HTML tags and attributes using AngularJS directives which make it easy to bind data directly to HTML elements.

AngularJS uses JavaScript objects to represent data called Scope which can be data generated on the web server, a database, web service, or client side AngularJS code.

You can use expressions that are directly linked to the scope (data) so that the page is updated dynamically as the data changes. Data binding works as well so that when data changes on the web page the model is also updated.

Many services are provided for common tasks like using AJAX techniques to dynamically pull data from a web service or the server.
*/

// Here we implement the template, module, controller and scope

// Define the AngularJS Module
// Modules are used to
// 1. Associate an AngularJS app with part of an HTML document
// 2. Provide access to AngularJS features
// 3. Help with organization
// angular.module() excepts the module name, list of modules this module
// needs and an optional configuration for the module. Modules that work with
// HTML normally have a name that contains app.
var app1 = angular.module('app1', []);

// Define the Controller and implement the Scope which links HTML
// elements to variables in the Scope. It receives the controller
// name and a factory function which gets the controller ready to use
// We are saying that $scope is a dependency and that we want Angular
// to pass in the $scope object when the function is called. This is
// an example of dependency injection. Angular sees that my factory
// function contains the $scope component and then it gets it and passes
// it to the function automatically.
app1.controller('ctrl1', function($scope) {

  // Define initial values
  $scope.first = 1;
  $scope.second = 1;

  // Change the value for calculation when the button is clicked
  // I used a shortcut using the unary plus operator to convert
  // the string number values which are then added
  $scope.updateValue = function() {
    $scope.calculation = $scope.first + ' + ' + $scope.second +
      " = " + (+$scope.first + +$scope.second);
  };
});

angulartut2.html

<!doctype html>
<html ng-app="app2">
  <head>
    <title>AngularJS Tutorial 2</title>
  </head>
  <body>
    <!-- You can create multiple views that use the same controller -->
    <h4 ng-controller="ctrl1">First Random Number : {{randomNum1}}</h4>
    <h4 ng-controller="ctrl1">Second Random Number : {{randomNum2}}</h4>

    <!-- A page can contain multiple controllers -->
    <h4 ng-controller="badCtrl">I'm feeling {{bad}}</h4>

    <h4 ng-controller="goodCtrl">I'm feeling {{good}}</h4>

    <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.4.9/angular.min.js"></script>
    <script src="js/exam2.js"></script>
  </body>
  </html>

exam2.js

var app2 = angular.module('app2', []);

app2.controller('ctrl1', function($scope) {

  $scope.randomNum1 = Math.floor((Math.random() * 10) + 1);
  $scope.randomNum2 = Math.floor((Math.random() * 10) + 1);

});

// Define multiple controllers
app2.controller('badCtrl', function($scope) {
  var badFeelings = ["Disregarded", "Unimportant", "Rejected", "Powerless"];

  $scope.bad = badFeelings[Math.floor((Math.random() * 4))];
});

app2.controller('goodCtrl', function($scope) {
  var goodFeelings = ["Pleasure", "Awesome", "Lovable", "Inner Peace"];

  $scope.good = goodFeelings[Math.floor((Math.random() * 4))];
});

angulartut3.html

<!doctype html>
<!-- ng-cloak is added so that HTML isn't shown in the document before AngularJS has had time to process it -->
<html ng-app="app3" ng-cloak>
  <head>
    <title>AngularJS Tutorial 3</title>

    <!-- Included when we wait to call AngularJS at the end of the document -->
    <style>
    [ng\:cloak], [ng-cloak], .ng-cloak {
      display: none;
    }
    </style>
  </head>
  <body>

    <div id="groceryList" ng-controller="gListCtrl">

      <!-- You can use data binding as an expression or
      with ng-bind -->
      <h3 class="ListTitle">{{groceries.length}} Groceries to Get</h3>
      <h3 class="ListTitle">
        <span ng-bind="groceries.length"></span> Groceries to Get</h3>

      <!-- You can list array items -->
      <ol style="margin: 0 0 -15px 0;">
        <li>{{groceries[0].item}}</li>
      </ol>

      <!-- List the rest of the groceries and skip the 1st index value. ng-repeat contains variables you can use such as $index, $first (true) if first item, $last (true if last item), $middle (true if not 1st or last), $even (true if even), $odd (true if odd) -->
      <ol start="2">
        <li ng-repeat = "grocery in groceries"
          ng-if="$index > 0">
          {{grocery.item}} {{$index}}
        </li>
      </ol>

      <!-- ng-repeat-start and ng-repeat-end allow us to use ng-repeat on 2 elements rather then on just one -->
      <table>
      <tr ng-repeat-start="grocery in groceries">
        <td>
          {{grocery.item}}
        </td>
        <tr ng-repeat-end>
          <td>
            {{grocery.purchased}}
          </td>
        </tr>
      </table>

      <!-- 2 way binding allows the user to change the data
      model -->
      <label>Change 1st Item : </label>
      <input ng-model="groceries[0].item" />

      <!-- ng-include inputs a HTML fragment into a page. If you get the error "Cross origin requests are only supported for protocol schemes" that is because this page must be served from a server.  -->
      <h3>Grocery List</h3>
      <div ng-include="'grocerylist.html'"></div>

      <!-- We can also dynamically load different HTML partials -->
      <label>
        <!-- showList will represent the HTML returned -->
        <input type="checkbox" ng-model="showList">
        Show Unordered List
      </label>
      <ng-include src="getList()"></ng-include>

      <!-- ng-switch allows us to conditionally insert or remove an element in the document -->
      <label>Type a number (1 to 4):
        <input type="text" ng-model="someNumber" />
      </label>
      <div ng-switch="someNumber">
        <p ng-switch-when="1">You entered 1</p>
        <p ng-switch-when="2">You entered 2</p>
        <p ng-switch-when="3">You entered 3</p>
        <p ng-switch-when="4">You entered 4</p>
        <p ng-switch-default="1">Not Following Directions</p>
      </div>

    </div>

    <!-- Load the AngularJS library -->
    <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.4.9/angular.min.js"></script>

    <!-- Load the JS Module -->
    <script src="js/exam3.js"></script>

  </body>
</html>

grocerylist.html

<ol>
  <li ng-repeat = "grocery in groceries">
    {{grocery.item}}
  </li>
</ol>

ulgrocerylist.html

<ul>
  <li ng-repeat = "grocery in groceries">
    {{grocery.item}}
  </li>
</ul>

exam3.js

/*
Directives allow you to extend HTML. There are many built in and youcan make
custom ones as well. Built in directives provide event handling, form
validation, templates and more.
*/

// Define the AngularJS Module
var app3 = angular.module('app3', []);

// Define the Controller and implement the Scope
app3.controller('gListCtrl', function($scope) {

  $scope.groceries = [
    {item: "Tomatoes", purchased: false},
    {item: "Potatoes", purchased: false},
    {item: "Bread", purchased: false},
    {item: "Hummus", purchased: false}
  ];

  // Return a different HTML partial based on whether the
  // checkbox is checked or not
  $scope.getList = function(){
    return $scope.showList ? "ulgrocerylist.html" : "grocerylist.html";
  };

});

angulartut4.html

<!doctype html>
<html ng-app="app4" ng-cloak>
  <head>
    <title>AngularJS Tutorial 4</title>
    <style>
    [ng\:cloak], [ng-cloak], .ng-cloak {
      display: none;
    }
    .bluetext {
      color:blue;
    }
    .boldtext {
      font-weight: bold;
    }
    .stripedblue {
      color:#007FFF;
      background-color:#DBE9F4;
    }
    .stripedbeige {
      color:#CC0000;
      background-color:#F5F5DC;
    }
    </style>
  </head>
  <body>
    <!-- AngularJS can respond to events -->
    <div ng-controller="eventCtrl">
      <!-- ng-change requires ng-model -->
      <input ng-blur="blur = blur + 1"
      ng-click="click = click + 1"
      ng-dblclick="dblclick = dblclick + 1"
      ng-copy="copy = copy + 1"
      ng-paste="paste = paste + 1"
      ng-cut="cut = cut + 1"
      ng-focus="focus = focus + 1"
      ng-model="confirmed"
      ng-change="change = change + 1"
      ng-keydown="keydown($event)"
      ng-mouseenter="mouseenter = mouseenter + 1"
      ng-mouseleave="mouseleave = mouseleave + 1"/>

      <h4>Blur Events : {{blur}}</h4>
      <h4>Click Events : {{click}}</h4>
      <h4>Double Click Events : {{dblclick}}</h4>
      <h4>Copy Events : {{copy}}</h4>
      <h4>Paste Events : {{paste}}</h4>
      <h4>Cut Events : {{cut}}</h4>
      <h4>Focus Events : {{focus}}</h4>
      <h4>Change Events : {{change}}</h4>

      <!-- There is also keypress and keyup -->
      <h4>Key Pressed : {{kdKey}}</h4>

      <!-- There is also mousedown, mousemove, mouseover and mouseup -->
      <h4>Mouse Enter Events : {{mouseenter}}</h4>
      <h4>Mouse Leave Events : {{mouseleave}}</h4>

      <!-- We can disable and inable elements -->
      <p>
        <button ng-disabled="disableButton">Button</button>
      </p>
      <p>
        <input type="checkbox" ng-model="disableButton">Disable Button
      </p>

      <!-- We can hide and show elements -->
      <p>
        <input type="checkbox" ng-model="daytimeButton">Morning
      </p>
      <p ng-hide="!daytimeButton">Good Morning</p>
      <p ng-hide="daytimeButton">Good Evening</p>

      <!-- We can dynamically change a class -->
      <p>
        <select ng-model="textStyling">
          <option value="bluetext">Blue Text</option>
          <option value="boldtext">Bold Text</option>
        </select>
      </p>
      <p ng-class="textStyling">Some Random Text</p>
    </div>

    <!-- We can bind classes on even elements with ng-class-even and/or ng-class-odd -->
    <table>
      <tr ng-repeat="item in capitals" ng-class-even="'stripedblue'"
      ng-class-odd="'stripedbeige'">
        <td>{{item.City}}</td>
        <td>{{item.State}}</td>
      </tr>
    </table>

    <!-- Load the AngularJS library -->
    <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.4.9/angular.min.js"></script>

    <!-- Load the JS Module -->
    <script src="js/exam4.js"></script>
  </body>
</html>

exam4.js

// Define the AngularJS Module
var app4 = angular.module('app4', []);

// Define the Controller and implement the Scope
app4.controller('eventCtrl', function($scope) {
  $scope.blur = 0;
  $scope.click = 0;
  $scope.dblclick = 0;
  $scope.copy = 0;
  $scope.paste = 0;
  $scope.cut = 0;
  $scope.focus = 0;
  $scope.change = 0;
  $scope.keydown = function(e) {
    // Works for the basic characters and numbers
    $scope.kdKey = String.fromCharCode(e.keyCode);
  };
  $scope.mouseenter = 0;
  $scope.mouseleave = 0;

  // Used to disable button
  $scope.disableButton = true;

  // Used to show and hide elements
  $scope.daytimeButton = true;

  // Used for table
  $scope.capitals = [
    {"City": "Montgomery",
    "State": "Alabama"},
    {"City": "Juneau",
    "State": "Alaska"},
    {"City": "Phoenix",
    "State": "Arizona"},
    {"City": "Little Rock",
    "State": "Arkansas"}
  ];
});

Leave a Reply

Your email address will not be published. Required fields are marked *