CSS saves a lot of work. It can control the layout of multiple
web pages all at once.
Manipulate Text
Colors,
 Boxes
What is CSS?
Cascading Style Sheets (CSS) is used to format the layout of a webpage.
With CSS, you can control the color, font, the size of text, the spacing
between elements, how elements are positioned and laid out, what background
images or background colors are to be used, different displays for different devices
and screen sizes, and much more!
Tip: The word cascading means that a style
applied to a parent element will also apply to all children elements within the
parent. So, if you set the color of the body text to "blue", all headings,
paragraphs, and other text elements within the body will also get the same color (unless you specify
something else)!
Using CSS
CSS can be added to HTML documents in 3 ways:
Inline - by using the style attribute inside HTML elements
Internal - by using a <style> element in the <head> section
External - by using a <link>
element to link to an external CSS file
The most common way to add CSS, is to keep the styles in external CSS
files. However, in this tutorial we will use inline and internal styles, because this is easier to
demonstrate, and easier for you to try it yourself.
Inline CSS
An inline CSS is used to apply a unique style to a single HTML element.
An inline CSS uses the style attribute of an HTML element.
The following example sets the text color of the <h1> element to blue,
and the text color of the <p> element to red:
Example
<h1 style="color:blue;">A Blue Heading</h1>
<p
style="color:red;">A red paragraph.</p>
Internal CSS
An internal CSS is used to define a style for a single HTML page.
An internal CSS is defined in the <head> section of an HTML page,
within a <style> element.
The following example sets the text color of ALL the <h1> elements
(on that page) to blue, and the text color of ALL the <p> elements to
red. In addition, the page will be displayed with a "powderblue" background
color:Â
Example
<!DOCTYPE html> <html> <head> <style>
body {background-color: powderblue;} h1  {color: blue;} p   {color: red;}
</style> </head> <body>
<h1>This is a
heading</h1> <p>This is a paragraph.</p>
</body> </html>
External CSS
An external style sheet is used to define the style for many HTML pages.
To use an external style sheet, add a link to it in the <head> section of each HTML page:
Example
<!DOCTYPE html> <html> <head>
 <link rel="stylesheet" href="styles.css">
</head> <body>
<h1>This is a heading</h1> <p>This is a paragraph.</p>
</body> </html>
The external style sheet can be written in any text editor. The file must not contain any
HTML code, and must be saved with a .css extension.
Here is what the "styles.css" file looks like:
"styles.css":
body { Â Â background-color: powderblue; } h1 { Â color: blue; } p { Â Â color: red; }
Tip: With an external style sheet, you can change the look of an entire web site, by changing one file!
CSS Colors, Fonts and Sizes
Here, we will demonstrate some commonly used CSS properties. You will learn
more about them later.
The CSS color property defines the text color to be used.
The CSS font-family property defines the font to be used.
The CSS font-size property defines the text size to be used.
Example
Use of CSS color, font-family and font-size properties:
<!DOCTYPE html>
<html> <head> <style> h1 {   color: blue;   font-family: verdana;   font-size: 300%; } p {
 color: red; Â
font-family: courier; Â font-size: 160%; } </style> </head> <body>
<h1>This is a heading</h1> <p>This is a paragraph.</p>
</body> </html>
CSS Border
The CSS border property defines a border
around an HTML element.
Tip: You can define a border for nearly all HTML elements.
Example
Use of CSS border property:Â
p { Â Â border: 2px
solid powderblue; }
CSS Padding
The CSS padding property defines a padding
(space) between the text and the border.
Example
Use of CSS border and padding properties:
p { Â border: 2px
solid powderblue; Â padding: 30px; }
CSS Margin
The CSS margin property defines a margin
(space) outside the border.
Example
Use of CSS border and margin properties:
p { Â border: 2px
solid powderblue; Â Â margin: 50px;
}
Link to External CSS
External style sheets can be referenced with a full URL or with a path relative to the current web page.
Example
This example uses a full URL to link to a style sheet:
Global functions should be avoided in JavaScript. They can easily be overwritten or destroyed by other scripts.
AngularJS modules reduces this problem, by keeping all functions local to the module.
When to Load the Library
While it is common in HTML applications to place scripts at the end of the element, it is recommended that you load the AngularJS library either in the or at the start of the .
This is because calls to angular.module can only be compiled after the library has been loaded.
The HTML container where the AngularJS application is displayed, is called the view.
The view has access to the model, and there are several ways of displaying model data in the view.
You can use the ng-bind directive, which will bind the innerHTML of the element to the specified model property:
Example
<p ng-bind="firstname"></p>
You can also use double braces {{}} to display content from the model:
Example
<p>First name: {{firstname}}</p>
Or you can use the ng-model directive on HTML controls to bind the model to the view.
The ng-model Directive
Use the ng-model directive to bind data from the model to the view on HTML controls (input, select, textarea)
Example
<input ng-model="firstname">
The ng-model directive provides a two-way binding between the model and the view.
Two-way Binding
Data binding in AngularJS is the synchronization between the model and the view.
When data in the model changes, the view reflects the change, and when data in the view changes, the model is updated as well. This happens immediately and automatically, which makes sure that the model and the view is updated at all times.
Applications in AngularJS are controlled by controllers. Read about controllers in the chapter.
Because of the immediate synchronization of the model and the view, the controller can be completely separated from the view, and simply concentrate on the model data. Thanks to the data binding in AngularJS, the view will reflect any changes made in the controller.
It is important to know which scope you are dealing with, at any time.
In the two examples above there is only one scope, so knowing your scope is not an issue, but for larger applications there can be sections in the HTML DOM which can only access certain scopes.
Example
When dealing with the ng-repeat directive, each repetition has access to the current repetition object:
Note that the $location service is passed in to the controller
as an argument. In order to use the service in the controller, it must be
defined as a dependency.
Why use Services?
For many services, like the $location service, it seems like you
could use objects that are already in the DOM, like the window.location
object, and you could, but it would have some limitations, at least for your
AngularJS application.
AngularJS constantly supervises your application, and for it to handle changes
and events properly, AngularJS prefers that you use the $location
service instead of the window.location object.
The $http Service
The $http service is one of the most common used services in AngularJS
applications. The service makes a request to the server, and lets your
application handle the response.
Example
Use the $http service to request data from the server:
Once you have created a service, and connected it to your application, you can use the service in any controller, directive, filter, or even inside other services.
To use the service inside a filter, add it as a dependency when defining the
filter:
The example above 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.
Properties
The response from the server is an object with 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 use to get header information.
You can also use the ng-repeat directive to make the same dropdown list:
Example
<select> <option ng-repeat="x in names">{{x}}</option> </select>
Because the ng-repeat directive repeats a block of HTML code for each item in an array, it can be used to create options in a dropdown list, but the ng-options directive was made especially for filling a dropdown list with options.
What Do I Use?
You can use both the ng-repeat directive and the ng-options directive:
Assume you have an array of objects:
$scope.cars = [ {model : "Ford Mustang", color : "red"}, {model : "Fiat 500", color : "white"}, {model : "Volvo XC90", color : "black"} ];
Example
Using ng-repeat:
<select ng-model="selectedCar"> <option ng-repeat="x in cars" value="{{x.model}}">{{x.model}}</option> </select>
<h1>You selected: {{selectedCar}}</h1>
When using the value as an object, use ng-value insead of value:
Example
<select ng-model="selectedCar"> <option ng-repeat="x in cars" ng-value="{{x}}">{{x.model}}</option> </select>
<h1>You selected a {{selectedCar.color}}{{selectedCar.model}}</h1>
Example
Using ng-options:
<select ng-model="selectedCar" ng-options="x.model for x in cars"> </select>
<h1>You selected: {{selectedCar.model}}</h1> <p>Its color is: {{selectedCar.color}}</p>
When the selected value is an object, it can hold more information, and your application can be more flexible.
We will use the ng-options directive in this tutorial.
The Data Source as an Object
In the previous examples the data source was an array, but we can also use an object.
<%@ Import Namespace="System.IO"%> <%@ Import Namespace="System.Data"%> <%@ Import Namespace="System.Data.OleDb"%> <% Response.AppendHeader("Access-Control-Allow-Origin", "*") Response.AppendHeader("Content-type", "application/json") Dim conn As OleDbConnection Dim objAdapter As OleDbDataAdapter Dim objTable As DataTable Dim objRow As DataRow Dim objDataSet As New DataSet() Dim outp Dim c conn = New OledbConnection("Provider=Microsoft.Jet.OLEDB.4.0;data source=Northwind.mdb") objAdapter = New OledbDataAdapter("SELECT CompanyName, City, Country FROM Customers", conn) objAdapter.Fill(objDataSet, "myTable") objTable=objDataSet.Tables("myTable")
outp = "" c = chr(34) for each x in objTable.Rows if outp <> "" then outp = outp & "," outp = outp & "{" & c & "Name" & c & ":" & c & x("CompanyName") & c & "," outp = outp & c & "City" & c & ":" & c & x("City") & c & "," outp = outp & c & "Country" & c & ":" & c & x("Country") & c & "}" next
outp ="{" & c & "records" & c & ":[" & outp & "]}" response.write(outp) conn.close %>
4. Server Code ASP.NET, Razor C# and SQL Lite
@{ Response.AppendHeader("Access-Control-Allow-Origin", "*") Response.AppendHeader("Content-type", "application/json") var db = Database.Open("Northwind"); var query = db.Query("SELECT CompanyName, City, Country FROM Customers"); var outp ="" var c = chr(34) } @foreach(var row in query){ if (outp != "") {outp = outp + ","} outp = outp + "{" + c + "Name" + c + ":" + c + @row.CompanyName + c + "," outp = outp + c + "City" + c + ":" + c + @row.City + c + "," outp = outp + c + "Country" + c + ":" + c + @row.Country + c + "}" } outp ="{" + c + "records" + c + ":[" + outp + "]}" @outp
AngularJS has directives for binding application data to the attributes of HTML DOM elements.
The ng-disabled Directive
The ng-disabled directive binds AngularJS application data to the disabled attribute of HTML elements.
If you want to show a section of HTML code when a button is clicked, and hide when the button is clicked again, like a dropdown menu, make the button behave like a toggle switch:
<p>The input's valid state is:</p> <h1>{{myForm.myInput.$valid}}</h1>
Form State and Input State
AngularJS is constantly updating the state of both the form and the input fields.
Input fields have the following states:
$untouched The field has not been touched yet
$touched The field has been touched
$pristine The field has not been modified yet
$dirty The field has been modified
$invalid The field content is not valid
$valid The field content is valid
They are all properties of the input field, and are either true or false.
Forms have the following states:
$pristine No fields have been modified yet
$dirty One or more have been modified
$invalid The form content is not valid
$valid The form content is valid
$submitted The form is submitted
They are all properties of the form, and are either true or false.
You can use these states to show meaningful messages to the user. Example, if a field is required, and the user leaves it blank, you should give the user a warning:
Example
Show an error message if the field has been touched AND is empty:
<input name="myName" ng-model="myName" required> <span ng-show="myForm.myName.$touched && myForm.myName.$invalid">The name is required.</span>
CSS Classes
AngularJS adds CSS classes to forms and input fields depending on their states.
The following classes are added to, or removed from, input fields:
ng-untouched The field has not been touched yet
ng-touched The field has been touched
ng-pristine The field has not been modified yet
ng-dirty The field has been modified
ng-valid The field content is valid
ng-invalid The field content is not valid
ng-valid-key One key for each validation. Example: ng-valid-required, useful when there are more than one thing that must be validated
ng-invalid-key Example: ng-invalid-required
The following classes are added to, or removed from, forms:
ng-pristine No fields has not been modified yet
ng-dirty One or more fields has been modified
ng-valid The form content is valid
ng-invalid The form content is not valid
ng-valid-key One key for each validation. Example: ng-valid-required, useful when there are more than one thing that must be validated
ng-invalid-key Example: ng-invalid-required
The classes are removed if the value they represent is false.
Add styles for these classes to give your application a better and more intuitive user interface.
To create your own validation function is a bit more tricky; You have to add a new directive to your application, and deal with the validation inside a function with certain specified arguments.
Example
Create your own directive, containing a custom validation function, and refer to it by using my-directive.
The field will only be valid if the value contains the character "e":
Then you must refer to the ngAnimate module in your application:
<body ng-app="ngAnimate">
Or if your application has a name, add ngAnimate as a dependency in your application module:
Example
<body ng-app="myApp">
<h1>Hide the DIV: <input type="checkbox" ng-model="myCheck"></h1>
<div ng-hide="myCheck"></div>
<script>
var app = angular.module('myApp', ['ngAnimate']);
</script>
What Does ngAnimate Do?
The ngAnimate module adds and removes classes.
The ngAnimate module does not animate your HTML elements, but when ngAnimate notice certain events, like hide or show of an HTML element, the element gets some pre-defined classes which can be used to make animations.
The directives in AngularJS who add/remove classes are:
ng-show
ng-hide
ng-class
ng-view
ng-include
ng-repeat
ng-if
ng-switch
The ng-show and ng-hide directives adds or removes a ng-hide class value.
The other directives adds a ng-enter class value when they enter the DOM, and a ng-leave attribute when they are removed from the DOM.
The ng-repeat directive also adds a ng-move class value when the HTML element changes position.
In addition, during the animation, the HTML element will have a set of class values, which will be removed when the animation has finished. Example: the ng-hide directive will add these class values:
ng-animate
ng-hide-animate
ng-hide-add (if the element will be hidden)
ng-hide-remove (if the element will be showed)
ng-hide-add-active (if the element will be hidden)
ng-hide-remove-active (if the element will be showed)
Animations Using CSS
We can use CSS transitions or CSS animations to animate HTML elements. This tutorial will show you both.
The ngRoute module helps your application to become a Single Page Application.
What is Routing in AngularJS?
If you want to navigate to different pages in your application, but you also want the application to be a SPA (Single Page Application), with no page reloading, you can use the ngRoute module.
The ngRoute module routes your application to different pages without reloading the entire application.
Example:
Navigate to "red.htm", "green.htm", and "blue.htm":
Define the $routeProvider using the config method of your application. Work registered in the config method will be performed when the application is loading.
Controllers
With the $routeProvider you can also define a controller for each "view".
Example:
Add controllers:
var app = angular.module("myApp", ["ngRoute"]); app.config(function($routeProvider) { $routeProvider .when("/", { templateUrl : "main.htm" }) .when("/london", { templateUrl : "london.htm", controller : "londonCtrl" }) .when("/paris", { templateUrl : "paris.htm", controller : "parisCtrl" }); }); app.controller("londonCtrl", function ($scope) { $scope.msg = "I love London"; }); app.controller("parisCtrl", function ($scope) { $scope.msg = "I love Paris"; });
The "london.htm" and "paris.htm" are normal HTML files, which you can add AngularJS expressions as you would with any other HTML sections of your AngularJS application.
<h1>London</h1> <h3>London is the capital city of England.</h3> <p>It is the most populous city in the United Kingdom, with a metropolitan area of over 13 million inhabitants.</p> <p>{{msg}}</p>
<h1>Paris</h1> <h3>Paris is the capital city of France.</h3> <p>The Paris area is one of the largest population centers in Europe, with more than 12 million inhabitants.</p> <p>{{msg}}</p>
Template
In the previous examples we have used the templateUrl property in the $routeProvider.when method.
You can also use the template property, which allows you to write HTML directly in the property value, and not refer to a page.
Example:
Write templates:
var app = angular.module("myApp", [
It is time to create a real AngularJS Application.
Make a Shopping List
Lets use some of the AngularJS features to make a shopping list, where you can add or remove items:
My Shopping List
{{x}}×
{{errortext}}
Application Explained
Step 1. Getting Started:
Start by making an application called myShoppingList, and add a controller named myCtrl to it.
The controller adds an array named products to the current $scope.
In the HTML, we use the ng-repeat directive to display a list using the items in the array.
Example
So far we have made an HTML list based on the items of an array:
The application has some errors, like if you try to add the same item twice, the application crashes. Also, it should not be allowed to add empty items.
We will fix that by checking the value before adding new items.
In the HTML, we will add a container for error messages, and write an error message when someone tries to add an existing item.
Example
A shopping list, with the possibility to write error messages:
<script>
var app = angular.module("myShoppingList", []); app.controller("myCtrl", function($scope) { $scope.products = ["Milk", "Bread", "Cheese"]; $scope.addItem = function () { $scope.errortext = ""; if (!$scope.addMe) {return;} if ($scope.products.indexOf($scope.addMe) == -1) { $scope.products.push($scope.addMe); } else { $scope.errortext = "The item is already in your shopping list."; } } $scope.removeItem = function (x) { $scope.errortext = ""; $scope.products.splice(x, 1); } });
</script
Try it Yourself
You can edit the examples online, and click on a button to
view the result.
AngularJS Example
<div ng-app="">
<p>Name: <input type="text" ng-model="name"></p>
<p>You wrote: {{ name }}</p>