AngularJS Filters

Toggle navigation
TUTORIAL HOME
AngularJS Filters
❮ Previous Next ❯
Filters can be added in AngularJS to format data.

AngularJS Filters
AngularJS provides filters to transform data:

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.
Adding Filters to Expressions
Filters can be added to expressions by using the pipe character |, followed by a filter.

The uppercase filter format strings to upper case:

Example

The name is {{ lastName | uppercase }}

»
The lowercase filter format strings to lower case:

Example

The name is {{ lastName | lowercase }}

»
Adding Filters to Directives
Filters are added to directives, like ng-repeat, by using the pipe character |, followed by a filter:

Example
The orderBy filter sorts an array:

     

  •     {{ x.name + ‘, ‘ + x.country }}
     

»
The currency Filter
The currency filter formats a number as currency:

Example

Price: {{ price | currency }}

»
Read more about the currency filter in our AngularJS currency Filter Reference

The filter Filter
The filter filter selects a subset of an array.

The filter filter can only be used on arrays, and it returns an array containing only the matching items.

Example
Return the names that contains the letter “i”:

     

  •     {{ x }}
     

»
Read more about the filter filter in our AngularJS filter Filter Reference

Filter an Array Based on User Input
By setting the ng-model directive on an input field, we can use the value of the input field as an expression in a filter.

Type a letter in the input field, and the list will shrink/grow depending on the match:


{{ x }}
Example

     

  •     {{ x }}
     

»
Sort an Array Based on User Input
Click the table headers to change the sort order::

Name Country
{{x.name}} {{x.country}}
By adding the ng-click directive on the table headers, we can run a function that changes the sorting order of the array:

Example

 

   

    <th ng-click="orderByMe('country')”>Country

 

 

   

   

 

Name
{{x.name}} {{x.country}}

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;
  }
});

»
Custom Filters
You can make your own filters by registering a new filter factory function with your module:

Example
Make a custom filter called “myFormat”:

       

  •         {{x | myFormat}}
       

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’];
});

»
The myFormat filter will format every other character to uppercase.

❮ Previous Next ❯

AngularJS AJAX – $http

Toggle navigation
TUTORIAL HOME
AngularJS AJAX – $http
❮ Previous Next ❯
$http is an AngularJS service for reading data from remote servers.

AngularJS $http
The AngularJS $http service makes a request to the server, and returns a response.

Example
Make a simple request to the server, and display the result in a header:

Today’s welcome message is:

{{myWelcome}}

var app = angular.module(‘myApp’, []);
app.controller(‘myCtrl’, function($scope, $http) {
    $http.get(“welcome.htm”)
    .then(function(response) {
        $scope.myWelcome = response.data;
    });
});

»
Methods
The example above uses the .get method of the $http service.

The .get method is a shortcut method of the $http service. There are several shortcut methods:

.delete()
.get()
.head()
.jsonp()
.patch()
.post()
.put()
The methods above are all shortcuts of calling the $http service:

Example
var app = angular.module(‘myApp’, []);
app.controller(‘myCtrl’, function($scope, $http) {
    $http({
        method : “GET”,
        url : “welcome.htm”
    }).then(function mySucces(response) {
        $scope.myWelcome = response.data;
    }, function myError(response) {
        $scope.myWelcome = response.statusText;
    });
});
»
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.
.status a number defining the HTTP status.
.statusText a string defining the HTTP status.
Example
var app = angular.module(‘myApp’, []);
app.controller(‘myCtrl’, function($scope, $http) {
    $http.get(“welcome.htm”)
    .then(function(response) {
        $scope.content = response.data;
        $scope.statuscode = response.status;
        $scope.statustext = response.statustext;
    });
});
»
To handle errors, add one more functions to the .then method:

Example
var app = angular.module(‘myApp’, []);
app.controller(‘myCtrl’, function($scope, $http) {
    $http.get(“wrongfilename.htm”)
    .then(function(response) {
        //First function handles success
        $scope.content = response.data;
    }, function(response) {
        //Second function handles error
        $scope.content = “Something went wrong”;
    });
});
»
JSON
The data you get from the response is expected to be in JSON format.

JSON is a great way of transporting data, and it is easy to use within AngularJS, or any other JavaScript.

Example: On the server we have a file that returns a JSON object containing 15 customers, all wrapped in array called records.

Take a look at the JSON object.

×
customers.php
{{data | json}}
Example
The ng-repeat directive is perfect for looping through an array:

     

  •     {{ x.Name + ‘, ‘ + x.Country }}
     

var app = angular.module(‘myApp’, []);
app.controller(‘customersCtrl’, function($scope, $http) {
    $http.get(“customers.php”).then(function(response) {
        $scope.myData = response.data.records;
    });
});

»
Application explained:

The application defines the customersCtrl controller, with a $scope and $http object.

$http is an XMLHttpRequest object for requesting external data.

$http.get() reads JSON data from https://www.Omegas.com/angular/customers.php.

On success, the controller creates a property, myData, in the scope, with JSON data from the server.

❮ Previous Next ❯

AngularJS Select Boxes

Toggle navigation
TUTORIAL HOME
AngularJS Select Boxes
❮ Previous Next ❯
AngularJS lets you create dropdown lists based on items in an array, or an object.

Creating a Select Box Using ng-options
If you want to create a dropdown list, based on an object or an array in AngularJS, you should use the ng-options directive:

Example

var app = angular.module(‘myApp’, []);
app.controller(‘myCtrl’, function($scope) {
    $scope.names = [“Emil”, “Tobias”, “Linus”];
});

»
ng-options vs ng-repeat
You can also use the ng-repeat directive to make the same dropdown list:

Example

{{x}}

»
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, and has at least one important advantage:

Dropdowns made with ng-options allows the selected value to be an object, while dropdowns made from ng-repeat has to be a string.

What Do I Use?
Assume you have an array of objects:

$scope.cars = [
    {model : “Ford Mustang”, color : “red”},
    {model : “Fiat 500”, color : “white”},
    {model : “Volvo XC90”, color : “black”}
];
The ng-repeat directive has its limitations, the selected value must be a string:

Example
Using ng-repeat:

{{x.model}}

You selected: {{selectedCar}}

»
When using the ng-options directive, the selected value can be an object:

Example
Using ng-options:

You selected: {{selectedCar.model}}

Its color is: {{selectedCar.color}}

»
When the selected value can be 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.

Assume you have an object with key-value pairs:

$scope.cars = {
    car01 : “Ford”,
    car02 : “Fiat”,
    car03 : “Volvo”
};
The expression in the ng-options attribute is a bit different for objects:

Example
Using an object as the data source, x represents the key, and y represents the value:

You selected: {{selectedCar}}

»
The selected value will always be the value in a key-value pair.

The value in a key-value pair can also be an object:

Example
The selected value will still be the value in a key-value pair, only this time it is an object:

$scope.cars = {
car01 : {brand : “Ford”, model : “Mustang”, color : “red”},
car02 : {brand : “Fiat”, model : “500”, color : “white”},
car03 : {brand : “Volvo”, model : “XC90”, color : “black”}
};
»
The options in the dropdown list does not have to be the key in a key-value pair, it can also be the value, or a property of the value object:

Example

»

❮ Previous Next ❯

AngularJS Tables

Toggle navigation
TUTORIAL HOME
AngularJS Tables
❮ Previous Next ❯
The ng-repeat directive is perfect for displaying tables.

Displaying Data in a Table
Displaying tables with angular is very simple:

AngularJS Example

 

   

   

 

{{ x.Name }} {{ x.Country }}

var app = angular.module(‘myApp’, []);
app.controller(‘customersCtrl’, function($scope, $http) {
    $http.get(“customers.php”)
    .then(function (response) {$scope.names = response.data.records;});
});

»
Displaying with CSS Style
To make it nice, add some CSS to the page:

CSS Style

table, th , td {
  border: 1px solid grey;
  border-collapse: collapse;
  padding: 5px;
}
table tr:nth-child(odd) {
  background-color: #f1f1f1;
}
table tr:nth-child(even) {
  background-color: #ffffff;
}

»
Display with orderBy Filter
To sort the table, add an orderBy filter:

AngularJS Example

 

   

   

 

{{ x.Name }} {{ x.Country }}

»
Display with uppercase Filter
To display uppercase, add an uppercase  filter:

AngularJS Example

 

   

   

 

{{ x.Name }} {{ x.Country | uppercase }}

»
Display the Table Index ($index)
To display the table index, add a

with $index:

AngularJS Example

 

   

   

   

 

{{ $index + 1 }} {{ x.Name }} {{ x.Country }}

»
Using $even and $odd
AngularJS Example

<td ng-if="$odd" style="background-color:#f1f1f1″>{{ x.Name }}

<td ng-if="$odd" style="background-color:#f1f1f1″>{{ x.Country }}

{{ x.Name }} {{ x.Country }}

»

❮ Previous Next ❯

AngularJS HTML DOM

Toggle navigation
TUTORIAL HOME
AngularJS HTML DOM
❮ Previous Next ❯
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.

AngularJS Example

Click Me!

Button

{{ mySwitch }}

»
Application explained:

The ng-disabled directive binds the application data mySwitch to the HTML button’s disabled attribute.

The ng-model directive binds the value of the HTML checkbox element to the value of mySwitch.

If the value of mySwitch evaluates to true, the button will be disabled:

Click Me!

If the value of mySwitch evaluates to false, the button will not be disabled:

Click Me!

The ng-show Directive
The ng-show directive shows or hides an HTML element.

AngularJS Example

I am visible.

I am not visible.

»
The ng-show directive shows (or hides) an HTML element based on the value of ng-show.

You can use any expression that evaluates to true or false:

AngularJS Example

12″>I am visible.

»
In the next chapter, there are more examples, using the click of a button to hide HTML elements.

The ng-hide Directive
The ng-hide directive hides or shows an HTML element.

AngularJS Example

I am not visible.

I am visible.

»

❮ Previous Next ❯

AngularJS SQL

Toggle navigation
TUTORIAL HOME
AngularJS SQL
❮ Previous Next ❯
AngularJS is perfect for displaying data from a Database. Just make sure the data is in JSON format.

Fetching Data From a PHP Server Running MySQL
AngularJS Example

 

   

   

 

{{ x.Name }} {{ x.Country }}

var app = angular.module(‘myApp’, []);
app.controller(‘customersCtrl’, function($scope, $http) {
    $http.get(“customers_mysql.php”)
    .then(function (response) {$scope.names = response.data.records;});
});

»
Fetching Data From an ASP.NET Server Running SQL
AngularJS Example

 

   

   

 

{{ x.Name }} {{ x.Country }}

var app = angular.module(‘myApp’, []);
app.controller(‘customersCtrl’, function($scope, $http) {
    $http.get(“customers_sql.htmlx”)
    .then(function (response) {$scope.names = response.data.records;});
});

»
Server Code Examples
The following section is a listing of the server code used to fetch SQL data.

Using PHP and MySQL. Returning JSON.
Using PHP and MS Access. Returning JSON.
Using ASP.NET, VB, and MS Access. Returning JSON.
Using ASP.NET, Razor, and SQL Lite. Returning JSON.
Cross-Site HTTP Requests
Requests for data from a different server (than the requesting page), are called cross-site HTTP requests.

Cross-site requests are common on the web. Many pages load CSS, images, and scripts from different servers.

In modern browsers, cross-site HTTP requests from scripts are restricted to same site for security reasons.

The following line, in our PHP examples, has been added to allow cross-site access.

header(“Access-Control-Allow-Origin: *”);
1. Server Code PHP and MySQL
<?php
header(“Access-Control-Allow-Origin: *”);
header(“Content-Type: application/json; charset=UTF-8”);

$conn = new mysqli(“myServer”, “myUser”, “myPassword”, “Northwind”);

$result = $conn->query(“SELECT CompanyName, City, Country FROM Customers”);

$outp = “”;
while($rs = $result->fetch_array(MYSQLI_ASSOC)) {
    if ($outp != “”) {$outp .= “,”;}
    $outp .= ‘{“Name”:”‘  . $rs[“CompanyName”] . ‘”,’;
    $outp .= ‘”City”:”‘   . $rs[“City”]        . ‘”,’;
    $outp .= ‘”Country”:”‘. $rs[“Country”]     . ‘”}’;
}
$outp ='{“records”:[‘.$outp.’]}’;
$conn->close();

echo($outp);
?>
2. Server Code PHP and MS Access
<?php
header(“Access-Control-Allow-Origin: *”);
header(“Content-Type: application/json; charset=ISO-8859-1”);

$conn = new COM(“ADODB.Connection”);
$conn->open(“PROVIDER=Microsoft.Jet.OLEDB.4.0;Data Source=Northwind.mdb”);

$rs = $conn->execute(“SELECT CompanyName, City, Country FROM Customers”);

$outp = “”;
while (!$rs->EOF) {
    if ($outp != “”) {$outp .= “,”;}
    $outp .= ‘{“Name”:”‘  . $rs[“CompanyName”] . ‘”,’;
    $outp .= ‘”City”:”‘   . $rs[“City”]        . ‘”,’;
    $outp .= ‘”Country”:”‘. $rs[“Country”]     . ‘”}’;
    $rs->MoveNext();
}
$outp ='{“records”:[‘.$outp.’]}’;

$conn->close();

echo ($outp);
?>
3. Server Code ASP.NET, VB and MS Access

<%@ 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

❮ Previous Next ❯

AngularJS Forms

Toggle navigation
TUTORIAL HOME
AngularJS Forms
❮ Previous Next ❯
Forms in AngularJS provides data-binding and validation of input controls.

Input Controls
Input controls are the HTML input elements:

input elements
select elements
button elements
textarea elements
Data-Binding
Input controls provides data-binding by using the ng-model directive.

The application does now have a property named firstname.

The ng-model directive binds the input controller to the rest of your application.

The property firstname, can be referred to in a controller:

Example

var app = angular.module(‘myApp’, []);
app.controller(‘formCtrl’, function($scope) {
    $scope.firstname = “John”;
});

»
It can also be referred to elsewhere in the application:

Example

First Name:

You entered: {{firstname}}

»
Checkbox
A checkbox has the value true or false. Apply the ng-model directive to a checkbox, and use its value in your application.

Example
Show the header if the checkbox is checked:

    Check to show a header:
   

My Header

»
Radiobuttons
Bind radio buttons to your application with the ng-model directive.

Radio buttons with the same ng-model can have different values, but only the selected one will be used.

Example
Display some text, based on the value of the selected radio button:

Pick a topic:
Dogs
Tutorials
Cars

»
The value of myVar will be either dogs, tuts, or cars.

Selectbox
Bind select boxes to your application with the ng-model directive.

The property defined in the ng-model attribute will have the value of the selected option in the selectbox.

Example
Display some text, based on the value of the selected option:

Select a topic:

   
    Dogs
    Tutorials
    Cars

»
The value of myVar will be either dogs, tuts, or cars.

An AngularJS Form Example
First Name:

Last Name:

RESET
form = {{user}}

master = {{master}}

Application Code

 
    First Name:

   

    Last Name:

   
   

    RESET</button>
 
 

form = {{{user}}

 

master = {{{master}}

var app = angular.module(‘myApp’, []);
app.controller(‘formCtrl’, function($scope) {
    $scope.master = {firstName: “John”, lastName: “Doe”};
    $scope.reset = function() {
        $scope.user = angular.copy($scope.master);
    };
    $scope.reset();
});

»
The novalidate attribute is new in HTML5. It disables any default browser validation.

Example Explained
The ng-app directive defines the AngularJS application.

The ng-controller directive defines the application controller.

The ng-model directive binds two input elements to the user object in the model.

The formCtrl controller sets initial values to the master object, and defines the reset() method.

The reset() method sets the user object equal to the master object.

The ng-click directive invokes the reset() method, only if the button is clicked.

The novalidate attribute is not needed for this application, but normally you will use it in AngularJS forms, to override standard HTML5 validation.

❮ Previous Next ❯

AngularJS Events

Toggle navigation
TUTORIAL HOME
AngularJS Events
❮ Previous Next ❯
AngularJS has its own HTML events directives.

AngularJS Events
You can add AngularJS event listeners to your HTML elements by using one or more of these directives:

ng-blur
ng-change
ng-click
ng-copy
ng-cut
ng-dblclick
ng-focus
ng-keydown
ng-keypress
ng-keyup
ng-mousedown
ng-mouseenter
ng-mouseleave
ng-mousemove
ng-mouseover
ng-mouseup
ng-paste
The event directives allows us to run AngularJS functions at certain user events.

An AngularJS event will not overwrite an HTML event, both events will be executed.

Mouse Events
Mouse events occur when the cursor moves over an element, in this order:

ng-mouseenter
ng-mouseover
ng-mousemove
ng-mouseleave
Or when a mouse button is clicked on an element, in this order:

ng-mousedown
ng-mouseup
ng-click
You can add mouse events on any HTML element.

Example
Increase the count variable when the mouse moves over the H1 element:

Mouse over me!

{{ count }}

var app = angular.module(‘myApp’, []);
app.controller(‘myCtrl’, function($scope) {
    $scope.count = 0;
});

»
The ng-click Directive
The ng-click directive defines AngularJS code that will be executed when the element is being clicked.

Example

Click me!

{{ count }}

var app = angular.module(‘myApp’, []);
app.controller(‘myCtrl’, function($scope) {
    $scope.count = 0;
});

»
You can also refer to a function:

Example

Click me!

{{ count }}

var app = angular.module(‘myApp’, []);
app.controller(‘myCtrl’, function($scope) {
    $scope.count = 0;
    $scope.myFunction = function() {
        $scope.count++;
    }
});

»
Toggle, True/False
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:

Click Me

Menu:
Pizza
Pasta
Pesce
Example

Click Me!

   

Menu:

   

Pizza

   

Pasta

   

Pesce

var app = angular.module(‘myApp’, []);
app.controller(‘myCtrl’, function($scope) {
    $scope.showMe = false;
    $scope.myFunc = function() {
        $scope.showMe = !$scope.showMe;
    }
});

»
The showMe variable starts out as the Boolean value false.

The myFunc function sets the showMe variable to the opposite of what it is, by using the ! (not) operator.

$event Object
You can pass the $event object as an argument when calling the function.

The $event object contains the browser’s event object:

Example

Mouse Over Me!

Coordinates: {{x + ‘, ‘ + y}}

var app = angular.module(‘myApp’, []);
app.controller(‘myCtrl’, function($scope) {
    $scope.myFunc = function(myE) {
        $scope.x = myE.clientX;
        $scope.y = myE.clientY;
    }
});

»

❮ Previous Next ❯

AngularJS Form Validation

TUTORIAL HOME
AngularJS Form Validation
❮ Previous Next ❯
AngularJS can validate input data.

Form Validation
AngularJS offers client-side form validation.

AngularJS monitors the state of the form and input fields (input, textarea, select), and lets you notify the user about the current state.

AngularJS also holds information about whether they have been touched, or modified, or not.

You can use standard HTML5 attributes to validate input, or you can make your own validation functions.

Client-side validation cannot alone secure user input. Server side validation is also necessary.

Required
Use the HTML5 attribute required to specify that the input field must be filled out:

Example
The input field is required:

The input’s valid state is:

{{myForm.myInput.$valid}}</h1>
»
E-mail
Use the HTML5 type email to specify that the value must be an e-mail:

Example
The input field has to be an e-mail:

The input’s valid state is:

{{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:

<span ng-show="myForm.myName.$touched && myForm.myName.$invalid”>The name is required.
»
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.

Example
Apply styles, using standard CSS:

input.ng-invalid {
    background-color: pink;
}
input.ng-valid {
    background-color: lightgreen;
}

»
Forms can also be styled:

Example
Apply styles for unmodified (pristine) forms, and for modified forms:

form.ng-pristine {
    background-color: lightblue;
}
form.ng-dirty {
    background-color: pink;
}

»
Custom Validation
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”:

var app = angular.module(‘myApp’, []);
app.directive(‘myDirective’, function() {
  return {
    require: ‘ngModel’,
    link: function(scope, element, attr, mCtrl) {
      function myValidation(value) {
        if (value.indexOf(“e”) > -1) {
          mCtrl.$setValidity(‘charE’, true);
        } else {
          mCtrl.$setValidity(‘charE’, false);
        }
        return value;
      }
      mCtrl.$parsers.push(myValidation);
    }
  };
});

»
Example Explained:
In HTML, the new directive will be referred to by using the attribute my-directive.

In the JavaScript we start by adding a new directive named myDirective.

Remember, when naming a directive, you must use a camel case name, myDirective, but when invoking it, you must use – separated name, my-directive.

Then, return an object where you specify that we require  ngModel, which is the ngModelController.

Make a linking function which takes some arguments, where the fourth argument, mCtrl, is the ngModelController,

Then specify a function, in this case named myValidation, which takes one argument, this argument is the value of the input element.

Test if the value contains the letter “e”, and set the validity of the model controller to either true or false.

At last, mCtrl.$parsers.push(myValidation); will add the myValidation function to an array of other functions, which will be executed every time the input value changes.

Validation Example

<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.4.8/angular.min.js“>

Validation Example

<form  ng-app="myApp"  ng-controller="validateCtrl"
name=”myForm” novalidate>

Username:

 
 
  <span ng-show="myForm.user.$error.required”>Username is required.

 

Email:

 
 
  <span ng-show="myForm.email.$error.required”>Email is required.

  <span ng-show="myForm.email.$error.email”>Invalid email address.
 

  <input type="submit"
  ng-disabled=”myForm.user.$dirty && myForm.user.$invalid ||
  myForm.email.$dirty && myForm.email.$invalid”>

var app = angular.module(‘myApp’, []);
app.controller(‘validateCtrl’, function($scope) {
    $scope.user = ‘John Doe’;
    $scope.email = ‘john.doe@gmail.com‘;
});

»
The HTML form attribute novalidate is used to disable default browser validation.

Example Explained
The AngularJS directive ng-model binds the input elements to the model.

The model object has two properties: user and email.

Because of ng-show, the spans with color:red are displayed only when user or email is $dirty and $invalid.

❮ Previous Next ❯

AngularJS and W3.CSS

AngularJS and W3.CSS
❮ Previous Next ❯
You can easily use w3.css style sheet together with AngularJS. This chapter demonstrates how.

W3.CSS
To include W3.CSS in your AngularJS application, add the following line to the head of your document:

<link rel="stylesheet" href="https://www.Omegas.com/w3css/3/w3.css“>
If you want to study W3.CSS, visit our W3.CSS Tutorial.

Below is a complete HTML example, with all AngularJS directives and W3.CSS classes explained.

HTML Code

<link rel="stylesheet" href="https://www.Omegas.com/w3css/3/w3.css“>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.4.8/angular.min.js“>

Users

 

   

   

   

 

 

   

   

   

 

Edit First Name Last Name
      <button class="w3-btn w3-ripple" ng-click="editUser(user.id)”>✎ Edit
   
{{ user.fName }} {{ user.lName }}

✎ Create New User

 

Create New User:

 

Edit User:

    First Name:
   
 

    Last Name:
   
 

    Password:
   
 

    Repeat:
   

✔ Save Changes

http://myUsers.js

»
Directives (Used Above) Explained
AngularJS Directive Description
<body ng-app Defines an application for the element
<body ng-controller Defines a controller for the element
<tr ng-repeat Repeats the

element for each user in users
<button ng-click Invoke the function editUser() when the element is clicked
<h3 ng-show Show the

s element if edit = true
<h3 ng-hide Hide the form if hideform = true, and hide the

element if edit = true
<input ng-model Bind the element to the application
<button ng-disabled Disables the element if error or incomplete = true
W3.CSS Classes Explained
Element Class Defines

w3-container A content container

w3-table A table

w3-bordered A bordered table

w3-striped A striped table
w3-btn A button
w3-green A green button
w3-ripple A ripple effect when you click the button
w3-input An input field
w3-border A border on the input field
JavaScript Code
myUsers.js
angular.module(‘myApp’, []).controller(‘userCtrl’, function($scope) {
$scope.fName = ”;
$scope.lName = ”;
$scope.passw1 = ”;
$scope.passw2 = ”;
$scope.users = [
{id:1, fName:’Hege’, lName:”Pege” },
{id:2, fName:’Kim’,  lName:”Pim” },
{id:3, fName:’Sal’,  lName:”Smith” },
{id:4, fName:’Jack’, lName:”Jones” },
{id:5, fName:’John’, lName:”Doe” },
{id:6, fName:’Peter’,lName:”Pan” }
];
$scope.edit = true;
$scope.error = false;
$scope.incomplete = false;
$scope.hideform = true;
$scope.editUser = function(id) {
  $scope.hideform = false;
  if (id == ‘new’) {
    $scope.edit = true;
    $scope.incomplete = true;
    $scope.fName = ”;
    $scope.lName = ”;
    } else {
    $scope.edit = false;
    $scope.fName = $scope.users[id-1].fName;
    $scope.lName = $scope.users[id-1].lName;
  }
};

$scope.$watch(‘passw1’,function() {$scope.test();});
$scope.$watch(‘passw2’,function() {$scope.test();});
$scope.$watch(‘fName’, function() {$scope.test();});
$scope.$watch(‘lName’, function() {$scope.test();});

$scope.test = function() {
  if ($scope.passw1 !== $scope.passw2) {
    $scope.error = true;
    } else {
    $scope.error = false;
  }
  $scope.incomplete = false;
  if ($scope.edit && (!$scope.fName.length ||
  !$scope.lName.length ||
  !$scope.passw1.length || !$scope.passw2.length)) {
     $scope.incomplete = true;
  }
};

});
JavaScript Code Explained
Scope Properties Used for
$scope.fName Model variable (user first name)
$scope.lName Model variable (user last name)
$scope.passw1 Model variable (user password 1)
$scope.passw2 Model variable (user password 2)
$scope.users Model variable (array of users)
$scope.edit Set to true when user clicks on ‘Create user’.
$scope.hideform Set to true when user clicks on ‘Edit’ or ‘Create user’.
$scope.error Set to true if passw1 not equal passw2
$scope.incomplete Set to true if any field is empty (length = 0)
$scope.editUser Sets model variables
$scope.$watch Watches model variables
$scope.test Tests model variables for errors and incompleteness

❮ Previous Next ❯

Design a site like this with WordPress.com
Get started