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:
» 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:
» 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:
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:
» 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:
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.
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
» 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”);
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”);
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
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:
» 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:
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.
» 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”:
» 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.
» 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; } };
}); 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