Any word that is underlined represents a "tooltip." You can hover over it and see some additional information about that particular term. Any edits to that functionality can be investigagted by heading out to tooltipster.com.
You set this up using the https://ajax.googleapis.com/ajax/libs/angularjs/1.6.4/angular.min.js in your header.
Be aware that the process of introducing an Angular dynamic into a page is a process referred to as "auto-bootstrapping." You'll see that spelled out below, but it's good to be aware of this terminology.
A) Auto Bootstrapping(back to top...)
Here's a great article from https://www.quora.com/What-are-the-differences-between-bootstrap-and-angular-js that spells out the difference between "auto-bootrapping" and Bootstrap.
Bootstrap:What it is?
It is a set of well structured CSS styles, Grid classes and JavaScript components. The people at Twitter developed it and now it's a part of open source community and almost any personal project or startup project uses it.
These common tools including styles, css classes, javascript components helps us to develop at a faster pace especially for those who doesn't have experience in frontend development.
What it's not?
It's not a frontend framework which provides structure to your application or common functionality like routing, controllers and models, MVC architecture etc.
AngularJS:What it is?
It is developed and maintained by Google and is one of the top 3 JavaScript Frameworks out there. It provides set of components to structure your app and organize the project. Made for ambitious JavaScript Single Page Applications, AngularJS provides tools to make life of Frontend Developers easier by providing set of guidelines and architecture to application.
What it's not ?
It doesn't provide CSS styles, Grid classes or JavaScript components like Modal, Tabs, Navigation Bar, Dropdown menu etc.
As far as "Auto Bootstrapping," here you go:
Angular initializes / bootstraps automatically upon DOMContentLoaded event or when the angular.js script is downloaded to the browser and the document.readyState is set to complete. At this point AngularJS looks for the ng-app directive. When the ng-app directive is found then Angular will:
Load the module associated with the directive.
Create the application injector.
Compile the DOM starting from the ng-app root element.
This process is called auto-bootstrapping.
<html>
<body ng-app="myApp">
<div ng-controller="Ctrl">Hello {{msg}}!</div>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.4.5/angular.min.js"></script>
<script>
var app = angular.module('myApp', []);
app.controller('Ctrl', function($scope) {
$scope.msg = 'Nik';
});
</script>
</body>
</html>
AngularJS - Manual Bootstrapping :
You can manually initialized your angular app by using angular.bootstrap() function. This function takes the modules as parameters and should be called within angular.element(document).ready() function. The angular.element(document).ready() function is fired when the DOM is ready for manipulation.
<html>
<body>
<div ng-controller="Ctrl">Hello {{msg}}!</div>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.4.5/angular.min.js"></script>
<script>
var app = angular.module('myApp', []);
app.controller('Ctrl', function($scope) {
$scope.msg = 'Nik';
});
//manual bootstrap process
angular.element(document).ready(function () { angular.bootstrap(document, ['myApp']); });
</script>
</body>
</html>
Note :
You should not use the ng-app directive when manually bootstrapping your app.
You should not mix up the automatic and manual way of bootstrapping your app.
Define modules, controller, services etc. before manually bootstrapping your app as defined in above examples.
A) The ng-app, ng-model and ng-bind Directives(back to top...)
From W3 Schools.com: "AngularJS directives are extended HTML attributes with the prefix ng- . The ng-app directive initializes an AngularJS application. The ng-init directive initializes application data. The ng-model directive binds the value of HTML controls (input, select, textarea) to application data."
You've got a couple of "ng directives" to consider.
The ng-app defines an AngularJS application. While this isn't the best illustration, think of "ng-app as a doctype, similiar to <!DOCTYPE html> in that you'll only do this once per page. You can have more than one Angular component on a page, but we'll look at that later. For the examples you see below, know that you have to declare the "ng-app" and you do that only once. All the examples you see are in iframes.
The ng-model directive binds the valut of HTML controls to app data
The ng-bind directive binds application data to the HTML view
Check this out:
<div ng-app=""> // this tells AngularJS that this div has an AngularJS app attached to it
<p>Input something in the input box:</p>
<p>Name: <input type="text" ng-model="name"></p> //the "model" directive is directing traffic and in this case it's saying that this input is "bound" to the AngularJS application variable that, in this instance, is called, "name"
<p ng-bind="name"></p> the "bind" directive couples / binds the innerHTML of the <p> element to the application variable called "name"
</div>
Here's what that looks like:
Input something in the input box:
Name:
B) The ng-init Directive(back to top...)
You use the "ng-init" syntax to initialize AngularJS variables. Here's what that looks like using "valid" HTML:
Like this:
<div data-ng-app="" data-ng-init="firstName='John'">
<p>The name is <span data-ng-bind="firstName"></span></p>
</div>
Here's what that looks like:
You can do the same thing with a more "pure" approach to Angular by doing it this way:
<div ng-app="" ng-init="firstName='John'">
<p>The name is <span data-ng-bind="firstName"></span></p>
</div>
A) Curly Braces
Angular JS expressions are written inside double curly braces like this {{ expression }} and Angular will output the data exactly where the expression is written.
It looks like this:
<div ng-app="">
<p>My first expression is {{5 + 5 }}</p>
</div>
...and you can use Angular expression syntax to bind AngularJS data to HTML elements just like the ng-bind directive...
<div ng-app="">
<p>Name: <input type ="text" ng-model="name"></p>
<p>{{name}}</p>
</div>
AngularJS modules define AngularJS applications and AngularJS controllers control AngularJS applications.
The code looks like this:
<div ng-app="myApp" ng-controller="myCtrl">
First Name: <input type="text" ng-model="firstName"><br>
Last Name: <input type="text" ng-model="lastName"><br>
<br>
Full Name: {{firstName + " " + lastName}}
</div>
<script>
var app = angular.module('myApp', []);
app.controller('myCtrl', function($scope) {
$scope.firstName= "John";
$scope.lastName= "Doe";
});
</script>
A) Break It Down...!
The first thing you're doing is defining the application:
var app=angular.module('mApp', []);
Once you've defined the app, you then build on that and go on to define the Controller...
app.contoller('myCtrl', function($scope) {
$scope.firstName="John";
$cope.lastName="Doe";
});
Now when you throw your HTML into the mix, you've got a cool, little responsive application happening...
<div ng-app="myApp" ng-controller="myCtrl"> //here's your "twenty thousand foot" directive, as far as defining your app and your controller
First Name: <input type="text" ng-model="firstName"><br>
Last Name: <input type="text" ng-model="lastName"><br>
<br>
Full Name: {{firstName + " " + lastName}} // notice the curly braces indicating an expression
</div>
//and then down here is where you're putting your actual script for the controller functionality. Notice too that the "ng-app" directive tells AngularJS that the <div> element is the "owner" of the AngularJS application.
Up to now we've mentioned AngularJS Directives in their most basic context as far as what's needed to get some rudimentary AngularJS functionality off the ground. Now, let's dig a little deeper.
A) ng-app, ng-init, ng-model(back to top...)
the "ng-app" directive initializes the AngularJS application by defining the root element and will automatically auto-bootstrap the application when the web page is loaded
The "ng-init" directive initializes application data - it defines initial values, although normally you won't use "ng-init," as much as you'll use a controller or module instead
The "ng-model" directive
binds the value of HTML controls (input, select, textarea) to application data
it can also provide type validation for application data (number, email, required)
provide status for application data (invalid, dirty, touched, error)
provide CSS classes for HTML elements
bind HTML elements for HTML forms
Here's an example:
...and here's the code:
<div ng-app="" ng-init="firstName='John'"> the "ng-app" directive defines the app and it also tells AngularJS that the <div> element is the "owner" of the AngularJS application
<p>Name: <input type="text" ng-model="firstName"></p>
<p>You wrote {{firstName}}</p> //the "{{firstName}}" expression is an AngularJS binding expression. {{firstName}} is bound with the ng-init directive
</div>B) Data Binding(back to top...)
Speaking of "data binding..."
You can get downright jiggy with it where Data Binding is concerned. Here's an example of how you can bind two text fields with two ng-model directives:
The code for this breaks down as follows:
<div ng-app="" ng-init="quantity=1;price=5"> //the "ng-app" directive tells AngularJS that the <div> element is the "owner of the AugularJS expression
Quantity: <input type="number" ng-model="quantity">
Costs: <input type="number" ng-model="price">
Total in dollar: {{ quantity * price }}
</div>//the "ng-init" directive binds both the quantity and the price variableC) Repeating HTML Elements(back to top...)
Here's the code:
<div ng-app="" ng-init="names=['Jani','Hege','Kai']">
<ul>
<li ng-repeat="x in names">
{{ x }}
</li>
</ul>
</div>
The "ng-repeat" directive actually clones HTML elements once for each item in a collection.
Look and see how it works with an array...
And here's that code:
<div ng-app="" ng-init="names=[
{name:'Jani',country:'Norway'},
{name:'Hege',country:'Sweden'},
{name:'Kai',country:'Denmark'}]">
<ul>
<li ng-repeat="x in names">
{{ x.name + ', ' + x.country }}
</li>
</ul>
</div>C) Create Your Own Directives
In addition to all of the pre-fabricated directives, you can create your own by using the .directive function.
To invoke the new directive, you make an HTML element with the same tag name as the new directive. The only difference is that you'll name the HTML element w3-test-directive and you'll name the directive itself w3TestDirective.
Check it out:
And here's the code:
<body style="white-space: normal;" ng-app="myApp">
<w3-test-directive></w3-test-directive>
<script>
var app=angular.module("myApp", []);
app.directive("w3TestDirective", function() {
return {
template:"<h1>Made by a directive</h1>"
};
});
</script>
</body>
...pretty cool!
And you can invoke an directive by using an Attribute:
<div w3-test-directive></div>
...or a Class:
<div class="w3-test-directive"></>
You can also restrict your directives to only be invoked by some of the methods. Click here to see that in action...
1) Restrict Your Directives
In some instances, you may want to restrict the way in which the directive can be invoked.
For example, say you had this on your page:
<w3-test-directive></w3-test-directive> //element
<div w3-test-directive></div> //attribute
You've got an an element and an attribute with the same name. If you wanted to see your directive invoked only by the attribute, you would code it like this:
var app = angular.module("myApp", []);
app.directive("w3TestDirective", function() {
return {
restrict : "A",
template : "<h1>Made by a directive!</h1>"
};
});
The legal restrict values are:
A) Basic Example
With the "ng-model" directive, you can bind the value of an input field to a variable created in AngularJS.
Check it out:
<div ng-app="myApp" ng-controller="myCtrl">
Name: <input ng-model="name">
</div>
<script>
var app = angular.module('myApp', []);
app.controller('myCtrl', function($scope) {
$scope.name="John Doe"; // with this one line of code, I'm dictating the value inside the input field above
});
</script>B) Two Way Binding
When you first look at the above code in practice, it's not that exciting. It just looks like an input field with a default value of "John Doe." But this works both ways. In the example above, the user can't change anything because the value is dictated by the "scope" formula. But you can set it up where the user can change the value and that will look like this:
<div ng-app="myApp" ng-controller="myCtrl">
Name: <input ng-model="name">
<h1>You entered: {{name}}</h1>
</div>
<script>
var app = angular.module('myApp', []);
app.controller('myCtrl', function($scope) {
$scope.name = "John Doe";
});
</script>
In real time, it looks like this:
C) Validate User Input
One of the practical ways in which you can use the "ng-model" directive is with data validation such as email, number and "required."
Like this:
<form ng-app="" name="myForm">
Email:
<input type="email" name="myAddress" ng-model="text">
<span ng-show="myForm.myAddress.$error.email">Not a valid email address</span>
</form>
That looks like this:
D) Application Status
Another way in which can be used is to evaluate the status of a certain field. For example (once again), an email field:
<form ng-app="" name="myForm" ng-init="myText = 'post@myweb.com'"> //define the app (ng-app) and the ng-init initializes the variable "myText" and gives it a value of "post@myweb.com"
Email:
<input type="email" name="myAddress" ng-model="myText" required> //the ng-model directive binds the "myText" variable to itself
<p>Edit the e-mail address, and try to change the status.</p>
<h1>Status</h1>
<p>Valid: {{myForm.myAddress.$valid}} (if true, the value meets all criteria).</p> //pre-manufactured functionality being switched on using $valid
<p>Dirty: {{myForm.myAddress.$dirty}} (if true, the value has been changed).</p>
<p>Touched: {{myForm.myAddress.$touched}} (if true, the field has been in focus).</p>
</form>
And here's how that looks:
E) CSS Classes
You can also guide and direct CSS classes like this:
The idea here is that the background color of the text field remains light blue (invalid) until the user populates with some kind of data.
Here's the code:
<style>
input.ng-invalid {
background-color:lightblue;
}
</style>
<form ng-app="" name="myForm">
Enter your name:
<input name="myName" ng-model="myText" required>
<span ng-show="myForm.myAddress.$error.email">Not a valid e-mail address</span>
</form>
You've got several classes to choose from as far as the way in which the ng-model can add or remove classes...
- ng-empty
- ng-not-empty
- ng-touched
- ng-untouched
- ng-valid
- ng-invalid
- ng-dirty
- ng-pending
- ng-pristine
The ng-model directive binds data from the model to the view on HTML controls (input, select, textarea).
A) Data Model(back to top...)
AngularJS applications usually have a data model which is a collection of data that's available for that particular app.
var app=angular.module('myApp', []);
app.controller('myCtrl', function($scope) {
$scope.firstname="John";
$scope.lastname="Doe";
}
B) HTML View(back to top...)
You then "bind" that data to specific HTML elements to "view" what the smoke is going on...
<p ng-bind="first_name"></p>
...and you can also use curly braces:
<p>First name: {{firstname}}</>
For example:
What you're looking at is this:
<script>
var app = angular.module('myApp', []);
app.controller('myCtrl', function($scope) {
$scope.firstname = "John";
$scope.lastname = "Doe";
});
</script>
<div ng-app="myApp" ng-controller="myCtrl">
<p>{{firstname}}</p>
</div>
C) Two-Way Binding(back to top...)
What's great is that you can also syncronize things in a way where you're using a text field and the value of that field can be changed OR it can be dictated by the Controller. By using a "two way binding" approach, you've got the best of both worlds working simultaneously.
So, instead of the <p> element, you've got this:
<div ng-app="myApp" ng-controller="myCtrl">
<input ng-model="lastname">
<h1>{{lastname}}</h1>
</div>
...and that looks like this:
A slight pause in order to reinforce the basics that have been covered thus far.
A) Directives(back to top...)1) app(back to top...)
First, you've got the "app" which will be a <div>. It's the div that serves as the parameters within which you've got your AngularJS application.
<div> ng-app=""div</>2) init(back to top...)
"init" is basically inititializing some AngularJS data and simultaneously giving it a name so it can be utilized in the context of an AngularJS app.
Like this:
<div ng-app="" ng-init="firstName='John'">
<p>Name: <input type="text" ng-model="firstName"></p> 3) model(back to top...)
The "model" - think of "Conjuction Junction" in that you're hooking things up. But instead of phrases and clauses, you're hooking HTML elements to AngularJS data.
Take, for example, an input field:
<input type="text" size="23" ng-model="firstName">
In this case, you've got an input field and you're using the "model" directive to link together the AngularJS data called "firstName" to the input field HTML element.
There are actually a great number of "directives" and you can see a comprehensive list by clicking here
What we've just looked at are the basic directives needed to get a rudimentary AngularJS app up and running. Real quick, let's do a rapid-fire summary of what we've looked at thus far that builds on those three elements.
B) Basic Concepts(back to top...)1) Binding and Expressions(back to top...)
An AngularJS expression is the syntax used that allows AngularJS to "express" itself.
In the example above we initialized a variable and a value for that variable with ng-init="firstName='John'" If we want to "express" that variable / value, we simply write {{ firstName }}. The curly braces are what defines an expression as just that.
The "binding" aspect of things comes into play just like mentioned earlier in the context of "models" in that you're "binding" or "coupling" HTML elements with AngularJS variables.
So, with the paragraph example we were working with before, we can do this:
<div ng-app="" ng-init="firstName='Bruce'">
<input type="text" size="23" ng-model="firstName" value="{{firstName]]">
<p>{{ firstName }}</p>
You see how we initialized the variable and the value of "firstName?" We then "bound" the <p> element to the "firstName" variable and when you see this happening in real life, you see the name, "Bruce" show up on the page. It actually shows up twice: Once in the input text field and once in the paragraph element that the "firstName" dynamic has been bound to.
When I change the value of the input field, it also changes the value in the AngularJS "firstName" var. This is what was referred to as "Two-Way Binding."
2) Models, Modules and Controllers(back to top...)
For whatever reason, "models," "modules" and "controllers" seem to run into one another as far as their meaning and functionality.
Again, "model" is a directive and we used the "Conjuction Junction" illustration to describe it. Similiar to the MVC architecture, it's dealing with data and its job is to couple AngularJS data with its corresonding HTML element. In that way, you can see the "ng-model" directive is similiar to the "view" in MVC. This is what we did a mere moment ago when we asserted the "ng-model" dynamic into the input text element.
A "module" and a "controller" go together. Think of a module as a container. Within that container you've got your "controller." If you think in terms of MVC, your "controller" is just like what you envision when you think of an MVC architecture in that your "Controller" in AngularJS is bringing your data and your GUI together.
Take note how now we're going to give the "ng-app" directive a value. That value will refer to the HTML element in which the app will run.
Here's an example:
<div ng-app="myApp" ng-controller="myCtrl">// you're going to assert a "controller" into the picture now
{{ firstName + " " + lastName }}
</div>
<script>
var app = angular.module("myApp", []); // you're going to use "angular.module" to define your module
app.controller("myCtrl", function($scope) {
$scope.firstName="John";
$scope.lastName="Doe";
});
</script>
That's enough for now, as far as review. Let's now pop the hood on some advanced info pertaining to Controllers. And, in case you're wondering, yes, we've used "$scope" but without really defining it. We're getting ready to do that.
Buckle up!
A) Objects(back to top...)
We've already seen this syntax before, let's just break it down a little bit more:
<div ng-app="myApp" ng-controller="myCtrl">// you're defining the application, stating that it's going to run inside this particular div and you're also defining the controller for this application
{{ firstName + " " + lastName }}
</div>
<script>
var app = angular.module("myApp", []); // remember a "module" is a container. In this case, it's a container that holds the "myApp" appliation
app.controller("myCtrl", function($scope) { // here's your controller (myCntrl) and you're invoking it with the $scope object
$scope.firstName="John"; //the controller creates two properties in the $scope object
$scope.lastName="Doe";
});
</script>An object in Javascript is simple a colleciton of properties...
...and a property is an association between a name (variable or key) and a value. A property's value can also be a function. Click here for more info.B) External Files and Methods(back to top...)
You can have methods (variables as functions) in your controllers and you can also have all of that code parked somewhere else as an external file.
For example, here's your controller:
var app = angular.module('myApp', []);
app.controller('personCtrl', function($scope) {
$scope.firstName="John";
$scope.lastName="Doe";
$scope.fullName= function() {
return $scope.firstName + " " + $scope.lastName;
};
});
Instead of including that on your page and taking up space, you can just reference it like this:
<script src="personController.js"></script>
Just remember that on the actual ".js" file, you don't need <script></script>.
Here's another example that's a little more advanced:
<div ng-app="myApp" ng-controller="namesCtrl">
<ul>
<li ng-repeat="x in names">
{{x.name+', ' + x.country}}
</li>
</ul>
</div>
<script src="namesController.js">
...and then your "namesController.js" file looks like this:
angular.module('myApp', []).controller('namesCtrl', function($scope) {
$scope.names = [
{name:'Jani', country: 'Norway'},
{name: 'Hegi', country: 'Sweden'},
{name:'Kai', country: 'Denmark'}
];
});
Put it all together and you've got this:
Adding a little more depth to the way in which we've looked at scopes thus far.
A) MVC Illustration(back to top...)
If you were going to look at the components we've considered thus far, you've got your "module," your "model" and your "controller."
Your "module" is your collection of AngularJS Objects etc.
Your "model" is your "Conjunction Junction" in the way it couples AngularJS data with specific HTML elements. If you're thinking in terms of the traditional MVC architecture, think of it as your "View"
Your "controller" is just like what you have with the MVC architecture in that the Controller facilitates the communication between your "view" and your "information" which is provided by your "scope..."
So, if you got back to some of the previous examples...
//"scope" is an object consisting of properties and values and in that way it serves as your "model" when you're thinking in terms of MVC
var app = angular.module('myApp', []);
app.controller('personCtrl', function($scope) {
$scope.firstName="John";
$scope.lastName="Doe";
$scope.fullName= function() {
return $scope.firstName + " " + $scope.lastName;
};
});B) Scope Usage(back to top...)
When you make a "controller," you pass the $scope object as an argument.
1) Arguments and Parameters(back to top...)
It's healthy to review these terms real quick.
In a function, you've got two primary entities: A "parameter" and an "argument."
A "parameter" is this:
function(parameter, paramater) {
do something...return something
}
An "argument" is a specific value that's passed in as one of the parameters.
So, if you've got something like this:
function id(x) { // "x" is a parameter
return x;
}
When you invoke / call that function, you would pass a variable into the function in order for it to do what's designed to accomplish. In this instance, you might pass a word into it like this:
function id('hello');
You would get "hello" back. The argument in this case, is "hello."
For more info, click here.
Now, going to back to AngularJS, you're passing the $object property into your controller as an argument.
app.controller('personCtrl', function($scope) { C) Root Scope(back to top...)
You have available to you something called "root scope" which looks like this:
<body ng-app="myApp">
The rootScope's favorite color is: {{color}}.
<div ng-controller="myCtrl">
The scope of the controller's favorite color is: {{color}}.
</div>
<script>
var app=angular.module('myApp', []);
app.run(function($rootScope) {
$rootScope.color='blue';
});
app.controller('myCtrl', function($scope) {
$scope.color="red";
});
</script>
</body>
Filters can be added to expression by using the pipe character (|), followed by a filter.
A) JS Filters(back to top...)
Here's a list of the filters that you have available...
currency Format a number to a currency format
date Format a date to a specified format
filter Select a subset of items from an array
json Format an object to a JSON string
limitTo Limits an array/string, into a specified number of elements/characters
lowercase Format a string to lower case
number Format a number to a string
orderBy Orders an array by an expression
uppercase Format a string to upper case
B) JS Filter Examples
Check it out:
1) uppercase(back to top...)<div ng-app="myApp" ng-controller="personCtrl">
<p>The name is {{ lastName | uppercase }}</p>
</div>
<script>
var app=angular.module('myApp', []).controller('personCtrl', function($scope)
{
$scope.firstName="Bruce",
$scope.lastName="Gust"
});
</script>
The result of what you see above is:
The name is GUST2) order by(back to top...)
You can add the "order by" filter and get the equivalent to a SELECT statement kind of thing:
Here's the code:
<div ng-app="myApp" ng-controller="namesCtrl">
<ul>
<li ng-repeat="x in names | orderBy: 'country'">
{{ x.name + ', ' + x.country }}
</li>
</ul>
</div>
<script>
var app=angular.module('myApp', []).controller('namesCtrl', function($scope)
{
$scope.names = [
{name:'Jani',country:'Norway'},
{name:'Carl',country:'Sweden'},
{name:'Margareth',country:'England'},
{name:'Hege',country:'Norway'},
{name:'Joe',country:'Denmark'},
{name:'Gustav',country:'Sweden'},
{name:'Birgit',country:'Denmark'},
{name:'Mary',country:'England'},
{name:'Kai',country:'Norway'}
];
});
</script>
...and here's what it looks like in person:
3) filter by(back to top...)
This option gives you the ability to filter by a particular character. In this case, we're filtering out every name that contains the letter, "i."
<div ng-app="myApp" ng-controller="namesCtrl">
<ul>
<li ng-repeat="x in names | filter: 'i'">
{{ x }}
</li>
</ul>
</div>
<script>
angular.module('myApp', []).controller('namesCtrl', function($scope)
{
$scope.names = [
'Jani',
'Carl',
'Margareth',
'Hege',
'Joe',
'Gustav',
'Birgit',
'Mary',
'Kai'
];
});
</script>
Here's what it looks like in person:
4) user input (very cool)(back to top...)
By using the "test" filter, you can weed out different options simply by typing some criteria into a text box.
Check it out:
<div ng-app="myApp" ng-controller="namesCtrl">
<p><input type="text" ng-model="test"></p>
<ul>
<li ng-repeat="x in names | filter : test">
{{ x }}
</li>
</ul>
</div>
<script>
angular.module('myApp', []).controller('namesCtrl', function($scope)
{
$scope.names = [
'Jani',
'Carl',
'Margareth',
'Hege',
'Joe',
'Gustav',
'Birgit',
'Mary',
'Kai'
];
});
</script>
And here it is, live and in person! Just type some letters into the text field and the list will automatically shrink based on the criteria you enter.
5) table sorter(back to top...)
All you have to do here is just click on the column name and you can sort things automatically. Very nice!
Here's the code:
<div ng-app="myApp" ng-controller="namesCtrl">
<table border="1" width="100%">
<tr>
<th ng-click="orderByMe('name')">Name</th>
<th ng-click="orderByMe('country')">Country</th>
</tr>
<tr ng-repeat="x in names | orderBy:myOrderBy">
<td>{{ x.name }}</td>
<td>{{ x.country }}</td>
</tr>
</table>
</div>
<script>
var app=angular.module('myApp', []).controller('namesCtrl', function($scope)
{
$scope.names = [
{name:'Jani',country:'Norway'},
{name:'Carl',country:'Sweden'},
{name:'Margareth',country:'England'},
{name:'Hege',country:'Norway'},
{name:'Joe',country:'Denmark'},
{name:'Gustav',country:'Sweden'},
{name:'Birgit',country:'Denmark'},
{name:'Mary',country:'England'},
{name:'Kai',country:'Norway'}
];
$scope.orderByMe = function(x) {
$scope.myOrderBy=x;
}
});
</script>
And here's the way it looks in real life:
6) custom sorter(back to top...)
This is a bizarre example, but here it is: You can create custom filters. This one makes it where every other letter is uppercase:
<ul ng-app="myApp" ng-controller="namesCtrl">
<li ng-repeat="x in names">
{{x | myFormat}}
</li>
</ul>
<script>
var app = angular.module('myApp', []);
app.filter('myFormat', function() {
return function(x) {
var i, c, txt = "";
for (i = 0; i < x.length; i++) {
c = x[i];
if (i % 2 == 0) {
c = c.toUpperCase();
}
txt += c;
}
return txt;
};
});
app.controller('namesCtrl', function($scope) {
$scope.names = [
'Jani',
'Carl',
'Margareth',
'Hege',
'Joe',
'Gustav',
'Birgit',
'Mary',
'Kai'
];
});
</script>
A) DOM Review(back to top...)1) DOM(back to top...)
In HTML you have what is called the DOM, which stands for "Document Object Model."
2) node(back to top...)
A "node," by definition, is "a point at which lines or pathways intersect or branch; a central or connecting point." So, in other words, it's a fancy way of describing a specific element. In the "DOM," you've got several "nodes." The document itself is a node, all of the HTML elements are nodes, text inside HTML elements are nodes.
3) Object(back to top...)
Javascript uses that paradigm to facilitate the ability to target specific aspects of the page and it stores all that information in an "object" called "window."
So, while in regular Javascript you would use "window.location," for example, as a "service" to direct the user to a different URL. With Angular, you're going to use something a little more verbose and effective.
Here is where you'll pick things up...
B) Location(back to top...)
Here's a service that prints the absolute URL of the page you're looking at:
<div ng-app="myApp" ng-controller="myCtrl">
The URL of this page is: <b>{{ myURL }} </b>
</div>
<br><br>
This example is using the "$location" service to the get absolute URL of this page.
<script>
var app = angular.module('myApp', []);
app.controller('myCtrl', function($scope, $location) {
$scope.myURL = $location.absUrl();
});
</script>
Real life...
C) http Service(back to top...)
This is a common request in the world of Angular JS. Here you're reaching out to a server and grabbing some content / data. Check it out:
<div ng-app="myApp" ng-controller="myCtrl">
Today's welcome message is coming from "wuddup.htm" and it reads:
<br><br>
{{myWelcome}}
</div>
<script>
var app=angular.module('myApp', []);
app.controller('myCtrl', function($scope, $http) {
$http.get("wuddup.htm").then(function (response) {
$scope.myWelcome = response.data;
});
});
</script><
In real life, it's this:
Bear in mind that the "wuddup.htm" page is nothing more than "Wuddup, dog?" There's no html info or code besides the text.
D) Timeout Service(back to top...)
You can use this service to display a message after two seconds:
<div ng-app="myApp" ng-controller="myCtrl">
This message change after two seconds. Wait for it...
<br><br>
{{myHeader}}
</div>
<script>
var app=angular.module('myApp', []);
app.controller('myCtrl', function($scope, $timeout) {
$scope.myHeader = "In 5-4-3-2-1...";
$timeout(function () {
$scope.myHeader = "See? I told you!";
}, 2000);
});
</script>
And...
E) Interval Service(back to top...)
You can use this to update a particular dynamic according to a specified timeframe. The most obvious application would that of a clock. Check it out:
<div ng-app="myApp" ng-controller="myCtrl">
The current time is:
<br><br>
{{theTime}}
</div>
<script>
var app=angular.module('myApp', []);
app.controller('myCtrl', function($scope, $interval) {
$scope.theTime = new Date().toLocaleTimeString();
$interval(function () {
$scope.theTime = new Date().toLocaleTimeString();
}, 1000); //"1000" will equate to updating the current time every second
});
</script>
Real world demo:
F) Custom Service(back to top...)
Here you're combining a service with a custom method, thus making it a unique, "customized" dynamic. With this function, we're converting a number into a hex value.
<div ng-app="myApp" ng-controller="myCtrl">
The hexadecimal value of 255 is:
<br><br>
{{hex}}
<br><br>
This is a custom service that converts a given number into a hexadecimal value.
</div>
<script>
var app=angular.module('myApp', []);
app.service('hexafy', function() {
this.myFunc = function(x) {
return x.toString(16);
}
});
app.controller('myCtrl', function($scope, hexafy) {
$scope.hex=hexafy.myFunc(255);
});
</script>
Here's what it looks like in real life:
F) Custom Service w/ Filter(back to top...)
You can take the above service and assert it as a filter. Like this:
<div ng-app="myApp" ng-controller="myCtrl">
Use a service as a filter when displaying the array [255, 251, 200]:
<br><br>
<ul><li ng-repeat="x in counts">{{x | myFormat}}</li></ul>
<br><br>
This filter uses a custom service that converts numbers into hexadecimal values.
</div>
<script>
var app=angular.module('myApp', []);
app.service('hexafy', function() {
this.myFunc = function(x) {
return x.toString(16);
}
});
app.filter('myFormat', ['hexafy', function(hexafy) {
return function(x) {
return hexafy.myFunc(x);
};
}]);
app.controller('myCtrl', function($scope) {
$scope.counts= [255,251,200];
});
</script>
The real deal:
This is an Angular service that reads data from remote servers. We went over this earlier in the context of "Services," but only in the context of an introduction. Here we get into some more verbose examples.
A) Simple "GET"
This, again, is a repeat of what we've already looked at...
<div ng-app="myApp" ng-controller="myCtrl">
Today's welcome message is coming from "wuddup.htm" and it reads:
<br><br>
{{myWelcome}}
</div>
<script>
var app=angular.module('myApp', []);
app.controller('myCtrl', function($scope, $http) {
$http.get("wuddup.htm").then(function (response) {
$scope.myWelcome = response.data;
});
});
</script><
In real life, it's this:
B) Methods
You can write this in a different way that makes use of a shortcut method. There are actually several shortcut methods that include:
.delete()
.get()
.head()
.jsonp()
.patch()
.post()
.put()
These are all shortcuts. Take a look at what the above syntax looks like when you're employing the "get" method using a "shortcut" approach:
var app=angular.module('myApp', []);
app.controller('myCtrl', function($scope, $http) {
$http({
method: "GET",
url: "wuddup.htm"
}).then(function mySuccess(response) {
$scope.myWelcome = response.data;
}, function myError(response) {
$scope.myWelcome = response.statusText;
});
});
The above example executes the $http service with an object as an argument. The object is specifying the HTTP method, the url, what to do on success and what to do on failure.
C) Properties
The great thing about the http service is that it's an object which, as we know, is a collection of both properties and values. So when we invoke this method you are, by default, accessing a fair amount of data and that can be very cool.
The response from the server, using the http service, is going to have these properties:
.config: the object used to generate the request
.data: a string, or an object, carrying the response from the server
.headers: a function to sue to get header information
.status: a number defining the HTTP status
.statusText: a string defining the HTTP status
Here's an example of that using the "wuddup.htm" example we've used in the last two sections:
<div ng-app="myApp" ng-controller="myCtrl">
Data: {{content}}<br>
Status: {{statuscode}}<br>
StatusText: {{statustext}}
</div>
<br>The response object has a number of properties. You're seeing a snippet of some of those listed above.
<script>
var app=angular.module('myApp', []);
app.controller('myCtrl', function($scope, $http) {
$http.get("wuddup.htm")
.then(function (response) {
$scope.content = response.data;
$scope.statuscode = response.status;
$scope.statustext = response.statusText;
});
});
</script>
And in the real world, it looks like this:
1) Error Messages
To handle errors, you just add one more function to the "then" method:
var app=angular.module('myApp', []);
app.controller('myCtrl', function($scope, $http) {
$http.get("wrongfilename.htm")
.then(function (response) {
//first function, by default, handles what happens when it works
$scope.content = response.data;
$scope.statuscode = response.status;
$scope.statustext = response.statusText;
}, function(response) {
// second function handle what happens when things go wrong
$scope.content = "Something went south!";
});
});
Remember, an object is a collection of properties and values. Click here for more info.
An "argument" is just a fancy way of defining the input data you're inserting into a function. It's coming from the world of mathematics.